MediumArrayBinary SearchMatrix

Search a 2D Matrix II

LeetCode
1 approach, code in all languages

You are given a matrix in which every row is sorted in ascending order from left to right and every column is sorted in ascending order from top to bottom. Given a target value, decide whether it exists somewhere in the matrix.

Unlike a fully sorted grid, the rows and columns are only individually sorted, so a plain binary search over a flattened view will not work. You need a strategy that exploits both orderings at once.

Example 1

Input: matrix = [[1, 4, 7], [2, 5, 8], [3, 6, 9]], target = 5

Output: true

Following the ordering from the top-right corner leads to the cell holding 5, so the target is present.

Example 2

Input: matrix = [[1, 4, 7], [2, 5, 8], [3, 6, 9]], target = 10

Output: false

The largest value in the matrix is 9, so 10 cannot be found anywhere.

Constraints

  • 1 <= m, n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row is sorted in ascending order
  • Each column is sorted in ascending order
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now