20. Search in Fully Rotated Sorted 2D Matrix
β GFG solution to Search in Fully Rotated Sorted 2D Matrix: efficiently find target element in rotated sorted matrix using modified binary search technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a 2D matrix mat[][] of size n x m that was initially filled in the following manner:
Each row is sorted in increasing order from left to right.
The first element of every row is greater than the last element of the previous row.
This implies that if the matrix is flattened row-wise, it forms a strictly sorted 1D array. Later, this sorted 1D array was rotated at some unknown pivot. The rotated array was then written back into the matrix row-wise to form the current matrix.
Given such a matrix mat[][] and an integer x, determine whether x exists in the matrix.
π Examples
Example 1
Input: x = 3,
mat[][] = [[7, 8, 9, 10],
[11, 12, 13, 1],
[2, 3, 4, 5]]
Output: true
Explanation: 3 is located at the 3rd row and 2nd column.Example 2
π Constraints
$1 \le n \times m \le 10^5$
$1 \le \text{mat}[i][j], x \le 10^6$
β
My Approach
The optimal approach treats the 2D matrix as a flattened 1D rotated sorted array and applies Modified Binary Search for rotated arrays:
Modified Binary Search on Rotated Matrix
Matrix Flattening Concept:
Treat the 2D matrix as a 1D array using index mapping:
mat[mid/m][mid%m]Use binary search pointers
l = 0andr = n*m - 1
Rotated Array Binary Search Logic:
At each iteration, determine which half is sorted by comparing
mat[l/m][l%m]withmat[mid/m][mid%m]If left half is sorted: check if target lies in the left sorted portion
If right half is sorted: check if target lies in the right sorted portion
Decision Making:
Left half sorted (
mat[l/m][l%m] <= mat[mid/m][mid%m]):If
mat[l/m][l%m] <= x < mat[mid/m][mid%m]: search left half (r = mid - 1)Otherwise: search right half (
l = mid + 1)
Right half sorted:
If
mat[mid/m][mid%m] < x <= mat[r/m][r%m]: search right half (l = mid + 1)Otherwise: search left half (
r = mid - 1)
Index Conversion:
Convert 1D index
ito 2D coordinates:row = i/m,col = i%mThis allows seamless navigation through the matrix as a linear array
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(log(nm)), where nm is the total number of elements in the matrix. We perform binary search on the flattened matrix, reducing search space by half in each iteration.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables like pointers and temporary values, regardless of the matrix size.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated