KatInterview

240. Search a 2D Matrix II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to efficiently find a target value in an m x n matrix. The matrix has a special structure: each row is sorted from left to right, and each column is sorted from top to bottom. A naive solution would be to check every cell, taking O(m * n) time. A better approach would be to use binary search on each row, resulting in O(m * log n) time. However, we can achieve an even more efficient solution by fully exploiting both sorted properties simultaneously.

Solution

Search a 2D Matrix II in Python

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        # According to constraints, matrix and matrix[0] are not empty.
        # But as a good practice, we can handle it.
        if not matrix or not matrix[0]:
            return False

        m, n = len(matrix), len(matrix[0])

        # Start the search from the top-right corner of the matrix.
        row, col = 0, n - 1

        # Loop until the pointers are out of the matrix bounds.
        while row < m and col >= 0:
            current = matrix[row][col]
            if current == target:
                # Found the target.
                return True
            elif current > target:
                # If the current element is greater than the target,
                # the target cannot be in the current column.
                # So, move to the left.
                col -= 1
            else:  # current < target
                # If the current element is smaller than the target,
                # the target cannot be in the current row.
                # So, move down.
                row += 1

        # If the loop finishes, the target was not found.
        return False

Search a 2D Matrix II in Java

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        // According to constraints, matrix and matrix[0] are not empty.
        // But as a good practice, we can handle it.
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }

        int m = matrix.length;
        int n = matrix[0].length;

        // Start the search from the top-right corner of the matrix.
        int row = 0;
        int col = n - 1;

        // Loop until the pointers are out of the matrix bounds.
        while (row < m && col >= 0) {
            int current = matrix[row][col];
            if (current == target) {
                // Found the target.
                return true;
            } else if (current > target) {
                // If the current element is greater than the target,
                // the target cannot be in the current column.
                // So, move to the left.
                col--;
            } else { // current < target
                // If the current element is smaller than the target,
                // the target cannot be in the current row.
                // So, move down.
                row++;
            }
        }

        // If the loop finishes, the target was not found.
        return false;
    }
}

Search a 2D Matrix II in C++

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        // According to constraints, matrix and matrix[0] are not empty.
        // But as a good practice, we can handle it.
        if (matrix.empty() || matrix[0].empty()) {
            return false;
        }

        int m = matrix.size();
        int n = matrix[0].size();

        // Start the search from the top-right corner of the matrix.
        int row = 0;
        int col = n - 1;

        // Loop until the pointers are out of the matrix bounds.
        while (row < m && col >= 0) {
            int current = matrix[row][col];
            if (current == target) {
                // Found the target.
                return true;
            } else if (current > target) {
                // If the current element is greater than the target,
                // the target cannot be in the current column.
                // So, move to the left.
                col--;
            } else { // current < target
                // If the current element is smaller than the target,
                // the target cannot be in the current row.
                // So, move down.
                row++;
            }
        }

        // If the loop finishes, the target was not found.
        return false;
    }
};

Search a 2D Matrix II in TypeScript

function searchMatrix(matrix: number[][], target: number): boolean {
    // According to constraints, matrix and matrix[0] are not empty.
    // But as a good practice, we can handle it.
    if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
        return false;
    }

    const m = matrix.length;
    const n = matrix[0].length;

    // Start the search from the top-right corner of the matrix.
    let row = 0;
    let col = n - 1;

    // Loop until the pointers are out of the matrix bounds.
    while (row < m && col >= 0) {
        const current = matrix[row][col];
        if (current === target) {
            // Found the target.
            return true;
        } else if (current > target) {
            // If the current element is greater than the target,
            // the target cannot be in the current column.
            // So, move to the left.
            col--;
        } else { // current < target
            // If the current element is smaller than the target,
            // the target cannot be in the current row.
            // So, move down.
            row++;
        }
    }

    // If the loop finishes, the target was not found.
    return false;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.