1497. Ones in a Sorted Grid

Medium3.5 points estimatedBinary SearchInteractiveMatrix

A seating chart marks each seat 0 (free) or 1 (taken) and is hidden behind a BinaryMatrix. Every row and every column of the chart is non-decreasing, so in each row the free seats come first, and the same holds down each column. matrix.dimensions() returns [rows, cols] and matrix.get(r, c) returns the value at row r, column c (0-based).

Return the total number of 1s in the chart. Start at the top-right cell: on a 1, every cell below it in that column is also 1, so count rows - r of them and step left; on a 0, step down. You may call matrix.get at most rows + cols times. Target O(rows + cols) time and O(1) extra space.

Example 1

Input:
matrix = [[0,0,1,1],[0,1,1,1],[1,1,1,1]]
Output:
9
Explanation:

The three rows hold 2, 3 and 4 ones respectively, so the total is 9.

Example 2

Input:
matrix = [[0,0],[0,0]]
Output:
0
Explanation:

Every seat is free, so the count is 0.

Example 3

Input:
matrix = [[1]]
Output:
1
Explanation:

The only cell is a 1, so the count is 1.

Constraints

1 ≤ rows, cols ≤ 100; dimensions() returns [rows, cols]; at most rows + cols calls to get

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Calls
You may call BinaryMatrix.get(row, col), BinaryMatrix.dimensions() at most 200 times per case. It is provided; you do not write it.

Expected complexity

Time
O(rows + cols)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…