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) ifiis within bounds - Returns
2³¹ - 1ifiis 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code