Search in Row and Column-wise Sorted Matrix Optimal Approach using Binary Search

Visualization Player

Problem Statement

You are given a 2D matrix where each row and each column is sorted in non-decreasing order. Your task is to search for a given target value in this matrix.

You need to determine whether the target value exists in the matrix or not. Return true if it exists, else return false.

The matrix is not fully sorted overall, but it has a special property:

  • Each row is sorted from left to right.
  • Each column is sorted from top to bottom.
This property allows us to use an efficient search technique rather than scanning every element.

Examples

Matrix Target Output Description
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
5 true
5 is present in the middle of the matrix
[[10, 20, 30], [15, 25, 35], [27, 29, 37]]
29 true
29 is present in the last row
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
10 false 10 is greater than all elements in the matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
0 false 0 is smaller than all elements in the matrix
[[5]]
5 true
Single element match
[[5]]
3 false Single element does not match
[]
1 false Empty matrix has no elements

Solution

Understanding the Problem

We are given a 2D matrix where each row and each column is sorted in non-decreasing order. Our goal is to determine whether a specific target value exists in the matrix.

This isn't just any matrix—its sorted nature gives us a big advantage. We don't have to search every cell. Instead, we can intelligently move through the matrix to find the target faster.

Step-by-Step Solution with Example

Step 1: Choose a Starting Point

We begin at the top-right corner of the matrix. Let’s say our matrix is:


int[][] matrix = {
  {1, 4, 7, 11},
  {2, 5, 8, 12},
  {3, 6, 9, 16},
  {10,13,14,17}
};
int target = 5;

The element at the top-right is 11. This choice is strategic because it allows us to eliminate either a row or a column based on the comparison with the target.

Step 2: Compare and Move

Compare the current element (starting at matrix[0][3] = 11) with the target:

  • If current element equals target → we found it!
  • If current element greater than target → move left (since elements to the left are smaller)
  • If current element less than target → move down (since elements below are larger)

Step 3: Walk Through the Example

  • Start at matrix[0][3] = 11. 11 > 5 → move left
  • Now at matrix[0][2] = 7. 7 > 5 → move left
  • Now at matrix[0][1] = 4. 4 < 5 → move down
  • Now at matrix[1][1] = 5. Match found!

We found the target in just 4 steps, without checking all 16 elements!

Step 4: Implement the Logic


public boolean searchMatrix(int[][] matrix, int target) {
  int rows = matrix.length;
  if (rows == 0) return false;
  int cols = matrix[0].length;

  int row = 0, col = cols - 1;

  while (row < rows && col >= 0) {
    if (matrix[row][col] == target) return true;
    else if (matrix[row][col] > target) col--;
    else row++;
  }
  return false;
}

Edge Cases

  • Empty Matrix: If the matrix is empty or has zero columns, return false immediately.
  • Single Element: If the matrix has one element, compare it directly with the target.
  • Target smaller than all elements: We’ll keep moving left and go out of bounds quickly.
  • Target greater than all elements: We’ll move down and exit the matrix without finding it.
  • Negative values or duplicates: Still handled correctly, as the sorted structure remains valid.

Finally

This method takes advantage of the matrix's sorted properties. By starting at the top-right, we are always moving closer to our goal and never backtracking. This makes the solution both intuitive and efficient.

The time complexity is O(N + M), where N is the number of rows and M is the number of columns. This is far better than a brute-force O(N * M) search.

For beginners, it’s a great example of how understanding data structure properties helps in writing optimized code.

Algorithm Steps

  1. Start at the top-right corner of the matrix, i.e., row = 0, col = M - 1.
  2. While row < N and col ≥ 0:
  3. → If mat[row][col] == target, return true.
  4. → If mat[row][col] > target, move left by doing col--.
  5. → If mat[row][col] < target, move down by doing row++.
  6. If the loop ends without finding the target, return false.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdbool.h>

bool searchMatrix(int mat[][3], int rows, int cols, int target) {
    int row = 0, col = cols - 1;
    while (row < rows && col >= 0) {
        if (mat[row][col] == target) return true;
        else if (mat[row][col] > target) col--; // Move left
        else row++; // Move down
    }
    return false;
}

int main() {
    int mat[3][3] = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
    int target = 5;
    printf("Element found: %s\n", searchMatrix(mat, 3, 3, target) ? "true" : "false");
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)When the target is found at the starting cell (top-right corner).
Average CaseO(N + M)In each step, we either eliminate a row or a column, leading to at most N + M steps.
Worst CaseO(N + M)In the worst case, the search visits one full row and one full column without finding the target.

Space Complexity

O(1)

Explanation: Only a few extra variables are used for row and column tracking, with no additional memory.

Problem Statement

You are given a 2D matrix where each row and each column is sorted in non-decreasing order. Your task is to search for a given target value in this matrix.

You need to determine whether the target value exists in the matrix or not. Return true if it exists, else return false.

The matrix is not fully sorted overall, but it has a special property:

  • Each row is sorted from left to right.
  • Each column is sorted from top to bottom.
This property allows us to use an efficient search technique rather than scanning every element.

Examples

Matrix Target Output Description
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
5 true
5 is present in the middle of the matrix
[[10, 20, 30], [15, 25, 35], [27, 29, 37]]
29 true
29 is present in the last row
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
10 false 10 is greater than all elements in the matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
0 false 0 is smaller than all elements in the matrix
[[5]]
5 true
Single element match
[[5]]
3 false Single element does not match
[]
1 false Empty matrix has no elements

Solution

Understanding the Problem

We are given a 2D matrix where each row and each column is sorted in non-decreasing order. Our goal is to determine whether a specific target value exists in the matrix.

This isn't just any matrix—its sorted nature gives us a big advantage. We don't have to search every cell. Instead, we can intelligently move through the matrix to find the target faster.

Step-by-Step Solution with Example

Step 1: Choose a Starting Point

We begin at the top-right corner of the matrix. Let’s say our matrix is:


int[][] matrix = {
  {1, 4, 7, 11},
  {2, 5, 8, 12},
  {3, 6, 9, 16},
  {10,13,14,17}
};
int target = 5;

The element at the top-right is 11. This choice is strategic because it allows us to eliminate either a row or a column based on the comparison with the target.

Step 2: Compare and Move

Compare the current element (starting at matrix[0][3] = 11) with the target:

  • If current element equals target → we found it!
  • If current element greater than target → move left (since elements to the left are smaller)
  • If current element less than target → move down (since elements below are larger)

Step 3: Walk Through the Example

  • Start at matrix[0][3] = 11. 11 > 5 → move left
  • Now at matrix[0][2] = 7. 7 > 5 → move left
  • Now at matrix[0][1] = 4. 4 < 5 → move down
  • Now at matrix[1][1] = 5. Match found!

We found the target in just 4 steps, without checking all 16 elements!

Step 4: Implement the Logic


public boolean searchMatrix(int[][] matrix, int target) {
  int rows = matrix.length;
  if (rows == 0) return false;
  int cols = matrix[0].length;

  int row = 0, col = cols - 1;

  while (row < rows && col >= 0) {
    if (matrix[row][col] == target) return true;
    else if (matrix[row][col] > target) col--;
    else row++;
  }
  return false;
}

Edge Cases

  • Empty Matrix: If the matrix is empty or has zero columns, return false immediately.
  • Single Element: If the matrix has one element, compare it directly with the target.
  • Target smaller than all elements: We’ll keep moving left and go out of bounds quickly.
  • Target greater than all elements: We’ll move down and exit the matrix without finding it.
  • Negative values or duplicates: Still handled correctly, as the sorted structure remains valid.

Finally

This method takes advantage of the matrix's sorted properties. By starting at the top-right, we are always moving closer to our goal and never backtracking. This makes the solution both intuitive and efficient.

The time complexity is O(N + M), where N is the number of rows and M is the number of columns. This is far better than a brute-force O(N * M) search.

For beginners, it’s a great example of how understanding data structure properties helps in writing optimized code.

Algorithm Steps

  1. Start at the top-right corner of the matrix, i.e., row = 0, col = M - 1.
  2. While row < N and col ≥ 0:
  3. → If mat[row][col] == target, return true.
  4. → If mat[row][col] > target, move left by doing col--.
  5. → If mat[row][col] < target, move down by doing row++.
  6. If the loop ends without finding the target, return false.

Code

C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdbool.h>

bool searchMatrix(int mat[][3], int rows, int cols, int target) {
    int row = 0, col = cols - 1;
    while (row < rows && col >= 0) {
        if (mat[row][col] == target) return true;
        else if (mat[row][col] > target) col--; // Move left
        else row++; // Move down
    }
    return false;
}

int main() {
    int mat[3][3] = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};
    int target = 5;
    printf("Element found: %s\n", searchMatrix(mat, 3, 3, target) ? "true" : "false");
    return 0;
}

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(1)When the target is found at the starting cell (top-right corner).
Average CaseO(N + M)In each step, we either eliminate a row or a column, leading to at most N + M steps.
Worst CaseO(N + M)In the worst case, the search visits one full row and one full column without finding the target.

Space Complexity

O(1)

Explanation: Only a few extra variables are used for row and column tracking, with no additional memory.


Comments

💬 Please keep your comment relevant and respectful. Avoid spamming, offensive language, or posting promotional/backlink content.
All comments are subject to moderation before being published.


Loading comments...