Search in 2D matrix II

Here are the detailed commercial-grade notes for the problem Search a 2D Matrix II from LeetCode:


Search-a-2d-matrix-ii


Problem Statement

Given an m x n matrix of integers where:

Implement an efficient algorithm that searches for a target value in this matrix. Return true if the target exists, otherwise return false.


Examples

Example 1:

Input:

matrix = [[1,4,7,11,15],
		  [2,5,8,12,19],        
		  [3,6,9,16,22],         
		  [10,13,14,17,24],         
		  [18,21,23,26,30]]  
target = 5

Output: true

Example 2:

Input:
Same matrix, target = 20
Output: false


Constraints


Intuition

We are given a matrix where both rows and columns are sorted, which rules out a simple binary search over the entire matrix directly. But it gives us a strong clue:

This two-pointer technique uses the sorted structure of the matrix to eliminate one row or one column in each step, ensuring O(m + n) time complexity.


Approach

  1. Start from the top-right corner: row = 0, col = n - 1

  2. Loop until you go out of matrix bounds:

    • If matrix[row][col] == target: return true

    • If matrix[row][col] > target: move leftcol--

    • Else: move downrow++

  3. If loop ends, return false


Java Code

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length;
        int n = matrix[0].length;
        int row = 0, col = n - 1;

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

        return false;
    }
}

Time and Space Complexity


Dry Run

Input:

matrix = [[1,4,7,11,15],
		  [2,5,8,12,19],        
		  [3,6,9,16,22],         
		  [10,13,14,17,24],         
		  [18,21,23,26,30]]  
target = 5

Steps:


Conclusion

This problem is a classic application of 2D matrix traversal using logical elimination, leveraging sorted properties of both rows and columns. Instead of brute force or nested binary searches, this O(m + n) solution is clean, intuitive, and efficient.

Whenever you're faced with a matrix sorted both row-wise and column-wise, consider starting from a corner (typically top-right or bottom-left) to apply this traversal technique.