Skip to main content

Search a 2D Matrix

Given a 2D matrix where: - Each row is sorted in ascending order - First element of each row > last element of previous row Return true if target exists in matrix, false otherwise Must use O(log(m*n)) time complexity Example: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 => true

Given a rectangular m by n integer matrix and an integer target, return true if target occurs in the matrix and false otherwise. Each row is sorted in non-decreasing order, and the first value of every row after the first is greater than the last value of the preceding row. An empty matrix or a matrix with no columns returns false. For a non-empty matrix, the search must take O(log(m * n)) time.

Examples

You write

search_matrix(matrix: List[List[int]], target: int)

  1. Example 1

    Input
    matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
    returns
    true
  2. Example 2

    Input
    matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
    returns
    false

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

Binary Search

I reach for it when

  • The input is sorted, or sorted and then rotated.
  • You want a boundary: the first or last place something is true.

Say this before you type. Say the yes-or-no question, and which side each answer throws away.

All 19 Binary Search problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Search Sorted 2D Matrixmedium

Prep guides that list this problem

Our company tags come from public interview write-ups. None of these is a confirmed question.