Skip to content
Onsite

Search a 2D Matrix II

MediumP2Coding

matrix is an m x n matrix where each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Rows are not required to continue from the end of the previous row.

Return true if target is in the matrix and false otherwise.

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

Example 3

Input
matrix = [[5]], target = 5
Output
true

Constraints

  • 1 <= m, n <= 300
  • -10^9 <= matrix[i][j], target <= 10^9
  • Rows and columns are each sorted in ascending order.

Hints

Run checks the 3 visible tests, Submit all 12.