You need to find a value in a sorted integer array secret, but you cannot see the array or its length. The only access you have is a reader object: reader.get(k) returns the element at index k (0-indexed), or 2**31 - 1 when k is outside the array.
Given the reader and an integer target, return the index k such that secret[k] == target, or -1 if target does not exist in the array. The array is sorted in ascending order and all of its values are unique.
Function Signature
def search(reader: ArrayReader, target: int) -> int:
Rules
-
The test harness builds
reader
from
secret
. Your function receives only
reader
and
target
. It has no access to
secret
or to its length.
-
reader.get(k)
returns
secret[k]
for
0 <= k < len(secret)
and
2147483647
(that is,
2**31 - 1
) for any other
k
.
-
The examples list
secret
only to describe the hidden array.
-
Values are unique, so when
target
is present its index is unique.
Constraints
-
1 <= len(secret) <= 10^4
-
-10^4 <= secret[i], target <= 10^4
-
secret
is sorted in ascending order.
-
All values in
secret
are unique.
Examples
Input: secret = [-1, 0, 3, 5, 9, 12], target = 9
Output: 4
The hidden array holds 9 at index 4: four values (-1, 0, 3, 5) come before it.
Input: secret = [-1, 0, 3, 5, 9, 12], target = 2
Output: -1
2 does not appear in the hidden array. It would fall between 0 and 3, and no element has that value.
Input: secret = [-1, 0, 3, 5, 9, 12], target = 12
Output: 5
12 is the last of six elements, so its index is 5. Any read at index 6 or beyond returns 2147483647.