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 SizeChallenge: Array size is unknown, but we need O(log n) search-10234?01234?ArrayReader Interface:reader.get(i) returns:• array[i] if i is valid index• 2³¹-1 if i is out of boundsTarget = 2 → Find index in O(log n) timeSolution: Exponential search + Binary search
Understanding the Visualization
1
Unknown Array
We have a sorted array but don't know its size
2
Interface
ArrayReader.get(i) returns element or 2³¹-1 if out of bounds
3
Goal
Find target index in O(log n) time
Key Takeaway
🎯 Key Insight: Use exponential doubling to find bounds, then binary search within those bounds for O(log n) complexity
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