Search in a Sorted Array of Unknown Size - Problem

This is an interactive problem. You have a sorted array of unique elements with an unknown size. You cannot directly access the array, but you can use the ArrayReader interface.

The ArrayReader.get(i) method:

  • Returns the value at index i (0-indexed) if i is within bounds
  • Returns 2³¹ - 1 if i is out of bounds

Given an integer target, return the index where the target exists in the hidden array, or -1 if it doesn't exist.

Constraint: Your algorithm must run in O(log n) time complexity.

Input & Output

Example 1 — Target Found
$ Input: secret = [-1,0,2,3,4], target = 2
Output: 2
💡 Note: Target 2 is found at index 2. First we find bounds by checking indices 1→2→4, then binary search between indices 2 and 4.
Example 2 — Target Not Found
$ Input: secret = [-1,0,3,5,9,12], target = 2
Output: -1
💡 Note: Target 2 is not in the array. We search through the bounds but don't find the target value.
Example 3 — Target at Beginning
$ Input: secret = [-1,0,3,5,9,12], target = -1
Output: 0
💡 Note: Target -1 is found at index 0, the very first position in the array.

Constraints

  • 1 ≤ secret.length ≤ 104
  • -104 ≤ secret[i], target ≤ 104
  • secret is sorted in ascending order
  • secret consists of unique elements

Visualization

Tap to expand
Search in Sorted Array of Unknown Size INPUT Hidden Array (unknown size) ? ? ? ? ? 0 1 2 3 4 Actual: [-1, 0, 2, 3, 4] ArrayReader Interface get(i) --> value at i out of bounds --> 2^31-1 Target 2 secret = [-1,0,2,3,4] target = 2 ALGORITHM STEPS 1 Find Search Bounds Start: left=0, right=1 2 Expand Right Bound Double right until get(right) >= target right: 1 --> 2 --> 4 get(1)=0 < 2 get(2)=2 >= 2 STOP 3 Binary Search Search in [left, right] left=0, right=2 mid=1, get(1)=0 < 2 mid=2, get(2)=2 == 2 4 Return Index Found at index 2 Time: O(log n) FINAL RESULT -1 0 2 3 4 0 1 2 3 4 FOUND! Output 2 Target 2 found at index 2 in the hidden array OK Key Insight: Since we cannot know the array size, we first expand the search boundary exponentially (doubling right) until we find a bound that contains the target. This takes O(log n) time. Then we perform standard binary search within those bounds, also O(log n). Total complexity: O(log n) + O(log n) = O(log n). TutorialsPoint - Search in a Sorted Array of Unknown Size | Optimal Solution
Asked in
Google 25 Facebook 18 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen