FastPrepStaircase Search In A Sorted Matrix

Staircase Search In A Sorted Matrix

Motive logoMotive● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given a nonempty rectangular integer matrix matrix and an integer target.

Every row is sorted in nondecreasing order from left to right. Every column is sorted in nondecreasing order from top to bottom. Adjacent rows are not required to form one globally sorted list.

Return true if target appears in matrix, and false otherwise.

Function

staircaseSearch(matrix: int[][], target: int) → boolean

Examples

Example 1

matrix = [[1,4,7],[2,5,8],[3,6,9]]target = 5return = true

Starting at the top-right value 7, move left because 5 is smaller, then move down because 4 is smaller than 5. The next cell is 5.

Example 2

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

The same walk from 7 reaches the bottom-right value 9 without seeing 10.

Constraints

  • 1 <= matrix.length, matrix[i].length <= 300.
  • matrix is rectangular: every row has the same length.
  • -10^9 <= matrix[i][j], target <= 10^9.
  • Each row is sorted nondecreasing left to right.
  • Each column is sorted nondecreasing top to bottom.

More Motive problems

See Motive hiring insights
public boolean staircaseSearch(int[][] matrix, int target) {
  // Write your code here.
}
matrix[[1,4,7],[2,5,8],[3,6,9]]
target5
expectedtrue
Checking account…