Algo-Sim › Matrix & Bit Manipulation

Search a 2D Matrix

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Find a target in a matrix whose rows read as one sorted list: binary search over the flattened index, mapping k to (k / n, k % n).

Problem

Each row of the m × n matrix is sorted, and each row starts with a value larger than the last value of the row above. Return true if target is in the matrix, in O(log(m·n)) time.

Constraints

Edge cases to test

Follow-up questions

Why one binary search instead of two?
Reading the rows end to end gives one sorted list of m·n values, so one search over index k with (k / n, k % n) is O(log mn).
What if only rows and columns are sorted separately?
Start at the top-right and drop a row or column per step: O(m + n) (LC 240).

Solution

Java

public boolean searchMatrix(int[][] matrix, int target) {
    int m = matrix.length, n = matrix[0].length;
    int lo = 0, hi = m * n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        int value = matrix[mid / n][mid % n];
        if (value == target) return true;
        if (value < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return false;
}

Python

def search_matrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    lo, hi = 0, m * n - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        value = matrix[mid // n][mid % n]
        if value == target:
            return True
        if value < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return False

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool searchMatrix(vector<vector<int>> &matrix, int target) {
        int m = int(matrix.size()), n = int(matrix[0].size());
        int lo = 0, hi = m * n - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int value = matrix[mid / n][mid % n];
            if (value == target)
                return true;
            if (value < target)
                lo = mid + 1;
            else
                hi = mid - 1;
        }
        return false;
    }
};

More Matrix & Bit Manipulation problems