1479. Measure the Hidden Shelf

Easy1.5 points estimatedBinary SearchInteractiveArray

A warehouse shelf holds an unknown number of boxes, each marked with an integer, and you cannot see how many there are. The only access is the object reader: reader.get(i) returns the mark of the box at position i (counting from 0), or 2147483647 when i is at or beyond the end of the shelf. Real marks are always smaller than that value.

Return the number of boxes on the shelf, making at most 32 calls to reader.get. Probe positions 1, 3, 7, 15, ... (each one is double the previous plus one) until the end marker shows up, then binary search the last window for the first position that returns the end marker; that position is the length.

The sample inputs show the shelf contents, but your code only sees them through reader. Aim for O(log length) time and O(1) extra space.

Example 1

Input:
reader = [5,-3,8]
Output:
3
Explanation:

Positions 0, 1 and 2 hold boxes and position 3 returns the end marker, so the length is 3.

Example 2

Input:
reader = [7]
Output:
1
Explanation:

A single box means position 1 is already beyond the end, so the length is 1.

Constraints

1 ≤ length ≤ 104

-104 ≤ values ≤ 104

at most 32 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 ArrayReader.get(index) at most 32 times per case. It is provided; you do not write it.

Expected complexity

Time
O(log n)
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…