← Back to index
MediumTypeScript2 min read

Search a 2D Matrix

binary search on a sorted 2d matrix by treating it as a flattened sorted array.

binary-searchmatrixarrays

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../search-a-2d-matrix/solution.tsTypeScript solution

since the matrix is sorted row-wise and each row starts after the previous ends, we can treat it as a single sorted array. i use binary search with index conversion: mid index maps to row = floor(mid / cols) and col = mid % cols.

this gives us O(log(mn)) time complexity, same as binary search on a flat array, but we work directly with the 2d structure.

key insight

the matrix is essentially a sorted array stored in row-major order. by converting linear indices to 2d coordinates, we can apply standard binary search.

complexity

O(log(mn)) time where m and n are dimensions, O(1) space. standard binary search efficiency.