Search in a Sorted Array of Unknown Size Problem
Description
LeetCode Problem 702.
This is an interactive problem.
You have a sorted array of unique elements and an unknown size. You do not have an access to the array but you can use the ArrayReader interface to access it. You can call ArrayReader.get(i) that:
- returns the value at the
i^thindex (0-indexed) of the secret array (i.e.,secret[i]), or - returns
2^31 - 1if theiis out of the boundary of the array.
You are also given an integer target.
Return the index k of the hidden array where secret[k] == target or return -1 otherwise.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: secret = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in secret and its index is 4.
Example 2:
Input: secret = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in secret so return -1.
Constraints:
1 <= secret.length <= 10^4-10^4 <= secret[i], target <= 10^4secretis sorted in a strictly increasing order.
Solution
Approach: Find a Bound, Then Binary Search
Binary search needs a right end, and we do not know the array's length. We find one by doubling: start with right = 1 and double it while reader.get(right) < target. Out-of-range indices return 2^31 - 1, which is larger than any target, so the loop stops at most one doubling after passing the end of the array.
When it stops, reader.get(right) >= target. The previous value right / 2 was smaller than the target (or it is index 0, if we never doubled). So the target, if it is in the array, lies in [right / 2, right].
Run an ordinary binary search on that range for the first index whose value is >= target. Out-of-range positions behave like huge values at the end of the array, so they need no special handling. Finally check whether the value at that index is exactly target, and return -1 if it is not.
Both phases make O(log k) calls, where k is the index of the target (or where it would be).
Complexity: O(log k) time and O(1) extra space.
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
#class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader: 'ArrayReader', target: int) -> int:
# Double the right end until it reaches a value >= target. Out-of-range reads
# return 2^31 - 1, which is larger than any target, so this always stops.
right = 1
while reader.get(right) < target:
right *= 2
left = right // 2
# Binary search [left, right] for the first value >= target.
while left < right:
mid = (left + right) // 2
if reader.get(mid) >= target:
right = mid
else:
left = mid + 1
return left if reader.get(left) == target else -1