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

  1. Matrix Flattening Concept:

    • Treat the 2D matrix as a 1D array using index mapping: mat[mid/m][mid%m]

    • Use binary search pointers l = 0 and r = n*m - 1

  2. Rotated Array Binary Search Logic:

    • At each iteration, determine which half is sorted by comparing mat[l/m][l%m] with mat[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

  3. 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)

  4. Index Conversion:

    • Convert 1D index i to 2D coordinates: row = i/m, col = i%m

    • This 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++)

⚑ View Alternative Approaches with Code and Analysis

πŸ’‘ Algorithm Steps:

  1. Find the pivot point where the array rotation occurs in the flattened matrix.

  2. Determine which half contains the target based on pivot position.

  3. Apply standard binary search on the identified sorted half.

  4. Handle edge cases where no rotation exists.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(log(n*m)) - Two binary searches

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space usage

βœ… Why This Approach?

  • Clear separation of pivot finding and searching

  • Easy to understand and debug

  • Reuses standard binary search logic

πŸ’‘ Algorithm Steps:

  1. Check each row individually to see if target can exist in that row.

  2. For each valid row, apply rotated array binary search.

  3. Use the property that each row is a rotated sorted array.

  4. Return true as soon as target is found in any row.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n * log m) - Binary search on each row

  • Auxiliary Space: πŸ’Ύ O(1) - Constant space usage

βœ… Why This Approach?

  • Leverages row-wise rotation property

  • Modular design with separate functions

  • Good when matrix has few rows

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Modified Binary Search

🟒 O(log(n*m))

🟒 O(1)

πŸš€ Optimal time complexity

πŸ”§ Complex rotation handling

πŸ” Pivot + Binary Search

🟒 O(log(n*m))

🟒 O(1)

πŸ“– Clear logic separation

πŸ› οΈ More code to maintain

πŸ“Š Row-wise Search

🟑 O(n * log m)

🟒 O(1)

🎯 Leverages row structure

🐌 Slower for wide matrices

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Modified Binary Search

β˜…β˜…β˜…β˜…β˜…

πŸ“– Code clarity priority

πŸ₯ˆ Pivot + Binary Search

β˜…β˜…β˜…β˜…β˜†

πŸ”§ Row-oriented data processing

πŸ₯‰ Row-wise Search

β˜…β˜…β˜…β˜†β˜†

β˜• 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

Visitor counter

Last updated