Problem 368125 · easy · Phase 03 Linear Management & Searching

Locate a Value in a Row-Major Sorted Grid

matrix · binary search · index arithmetic

matrix is an m x n grid of integers with these properties: each row is sorted in strictly increasing order, and the first value of every row is greater than the last value of the previous row. In other words, reading the grid row by row gives one strictly increasing sequence.

Return the position [row, col] of target, or [-1, -1] if it is not present.

Examples

Input:  matrix = [[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], target = 16
Output: [1, 2]

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

Constraints

  • 0 <= m, n <= 1000; matrix may be [].
  • Target: O(log(m * n)) time, O(1) space.

Goals

  • Treat a 2D grid as one flat sorted sequence
  • Convert a flat index into (row, column) with divmod
  • Run a binary search in logarithmic time
Starting Python…