Taro Logo

Search a 2D Matrix II

#128 Most AskedMedium
Topics:
ArraysBinary Search

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

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: 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 = 20
Output: false

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -109 <= matrix[i][j] <= 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 <= target <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the dimensions ($m$ and $n$) of the matrix, and can the matrix be empty or ragged (i.e., rows of varying lengths)?
  2. Can the matrix contain negative numbers, zeros, or floating-point values, or are we strictly dealing with standard integers?
  3. Could the target value appear multiple times within the matrix, or is it guaranteed to be unique if present?
  4. What should be returned if the matrix is completely empty or null?
  5. Are we guaranteed that the matrix dimensions are at least 1x1, or should I handle single-element matrices as a special edge case?

Brute Force Solution

Approach

Imagine you are looking for a specific hidden item in a grid filled with many items. The brute force approach simply means checking every single spot in the grid one by one until you either find what you are looking for or run out of spots.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first spot in the grid, usually starting from the top left corner.
  2. Check if the item sitting in that spot matches the one you are trying to find.
  3. If it matches, you have successfully found your answer and can stop searching.
  4. If it does not match, move on to the next spot in the grid.
  5. Continue moving through every single spot in the grid, one by one, checking each item you encounter.
  6. If you check every spot in the entire grid and still have not found a match, conclude that the item is definitely not in the grid.

Code Implementation

def search_matrix(matrix, target):    # Ensure the matrix is not empty to prevent out of bounds errors during traversal    if not matrix or not matrix[0]:        return False    row_count = len(matrix)    column_count = len(matrix[0])    # Iterate through every row and column combination to inspect all elements    for row_index in range(row_count):        for column_index in range(column_count):            current_element = matrix[row_index][column_index]            # Compare current grid element with target to determine if it is a match            if current_element == target:                return True    # Complete the search over all spots before concluding the target is absent    return False

Big(O) Analysis

Time Complexity
O(m * n) – The brute force approach uses nested loops to systematically check every single spot in the grid one by one, where m represents the number of rows and n represents the number of columns. For each of the m rows, we must traverse and check all n columns to see if the item matches our target. This exhaustive search requires us to visit m multiplied by n total positions in the worst-case scenario. This leads to approximately m * n operations, which simplifies to the Big O time complexity of O(m * n).
Space Complexity
O(1) – The provided brute force approach uses only a constant number of primitive variables to track the current row and column indices being checked in the grid. No auxiliary data structures, temporary lists, or recursion stack frames are created during the search process. As the grid size grows to contain N total elements, the extra memory required remains entirely fixed. Therefore, the total auxiliary space complexity simplifies to O(1).

Optimal Solution

Approach

Instead of searching every single number in the grid, the optimal approach starts at a clever corner where we can eliminate a whole row or column with a single comparison. By strategically moving away from that corner based on what we see, we quickly zero in on our target.

Here's how the algorithm would work step-by-step:

  1. Begin your search at the top-right corner of the grid, because this position has a special property: everything below it is larger, and everything to the left of it is smaller.
  2. Look at the number currently sitting at your position and compare it to the target number you are trying to find.
  3. If the number you are looking at is an exact match to your target, you have successfully found it and can stop.
  4. If the number you are looking at is larger than your target, you know that everything to the right in that same row is even larger, so you can safely move one step to the left to try a smaller number.
  5. If the number you are looking at is smaller than your target, you know that everything above in that same column is even smaller, so you can safely move one step down to try a larger number.
  6. Repeat this process of stepping left or down based on your comparisons.
  7. If you step entirely off the edge of the grid without finding a match, you can be certain the target number does not exist inside the grid.

Code Implementation

class Solution:
    def search_matrix(self, matrix: list[list[int]], target_value: int) -> bool:
        if not matrix or not matrix[0]:
            return False

        row_index = 0
        column_index = len(matrix[0]) - 1

        while row_index < len(matrix) and column_index >= 0:
            current_element = matrix[row_index][column_index]

            # Exact match found means we can terminate early and return true.
            if current_element == target_value:
                return True

            # Element is too large, eliminate current column by moving left.
            elif current_element > target_value:
                column_index -= 1

            # Element is too small, eliminate current row by moving down.
            else:
                row_index += 1

        # Stepping off the grid bounds confirms the target does not exist.
        return False

Big(O) Analysis

Time Complexity
O(m + n) – In the worst-case scenario, our search starts at the top-right corner and we must either traverse all the way down to the bottom row or all the way left to the first column to find the target or exit the grid. At each step of this traversal, we decrement the column index by one or increment the row index by one, meaning we move at most one step per row (m) and one step per column (n). This results in a maximum of m plus n total operations, which simplifies to O(m + n) time complexity where m is the number of rows and n is the number of columns.
Space Complexity
O(1) – To search the grid, the algorithm only maintains a pair of scalar variables to track the current row and column indices at the top-right corner. It does not allocate any temporary lists, hash maps, or recursive call stacks during execution. Because these few primitive pointer variables require a constant amount of memory regardless of the matrix dimensions, the auxiliary space remains entirely fixed. Thus, the total extra memory simplifies in Big O notation to O(1).

Edge Cases

Empty matrix or null matrix input
How to Handle:
Check if the matrix is null or has zero rows or columns and return false immediately.
Matrix with dimensions 1x1
How to Handle:
The search pointer starts at the single element and correctly compares it to the target.
Target is smaller than the smallest element or larger than the largest element
How to Handle:
The search bounds will step out of the matrix dimensions, safely terminating with a false return value.
Target is located at the extreme corners of the matrix
How to Handle:
The top-right or bottom-left starting strategy ensures these boundary positions are evaluated efficiently.
Matrix containing negative numbers, zeros, and positive numbers
How to Handle:
The sorted order properties hold regardless of sign, so relative comparisons remain mathematically valid.
Matrix with all identical values
How to Handle:
The directional search logic will consistently move in one direction until it matches or exhausts bounds.
Maximum-sized inputs near memory or time constraints
How to Handle:
The linear time complexity approach avoids extra space and easily processes large matrices within limits.
Target exists multiple times within the matrix
How to Handle:
The boolean search requirement means returning true upon the first encountered match is sufficient.
0/245 completed