621. Search in a Sorted Array of Unknown Size
You are given a read-only interface ArrayReader to access a secret sorted array of unique integers whose length is unknown. Implement a function that uses the reader to find the index of a given target.
ArrayReader.get(i) behaves as follows:
- Returns the value at index i (0-indexed) of the secret array (secret[i]) if i is within bounds.
- Returns 231 - 1 if i is out of bounds (i.e., beyond the end of the array).
Write an algorithm that returns the index k such that secret[k] == target. If the target is not present, return -1.
Your solution must run in O(log n) time where n is the length of the secret array.
Example 1:
Input: (hidden) secret = [1, 4, 6, 8, 15, 20], target = 15
Output: 4
Explanation: 15 exists in the array at index 4.
Example 2:
Input: (hidden) secret = [-10, -5, 0, 1, 3, 7, 100], target = -10
Output: 0
Explanation: -10 is the first element (index 0). Calls to ArrayReader.get(i) for large i return 2^31 - 1.
Now Your Turn!
Pick the correct output for the given inputInput: (hidden) secret = [2, 5, 9, 14, 18], target = 14
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= secret.length <= 104
- -104 <= secret[i], target <= 104
- secret is sorted in strictly increasing order.
- ArrayReader.get(i) == 231 - 1 for any i that is out of bounds.