Search in a Sorted Array of Unknown Size - Problem
Imagine you're given access to a mystery sorted array through a special interface, but here's the catch - you don't know how big it is!
You have an ArrayReader interface that lets you peek at elements using ArrayReader.get(i):
- Returns the value at index
iif it's within bounds - Returns
2ยณยน - 1(2147483647) if you've gone beyond the array's end
Your mission: Find the index where a target value is hiding in this mysterious sorted array, or return -1 if it doesn't exist.
The challenge? You must solve this in O(log n) time complexity - no linear scanning allowed!
Example: If the hidden array is [1, 3, 5, 7, 9] and target is 5, you should return 2.
Input & Output
example_1.py โ Basic Search
$
Input:
secret = [1, 3, 5, 7, 9], target = 5
โบ
Output:
2
๐ก Note:
The target value 5 is located at index 2 in the sorted array. Our algorithm first finds the boundary by checking positions exponentially, then performs binary search.
example_2.py โ Target Not Found
$
Input:
secret = [1, 3, 5, 7, 9], target = 6
โบ
Output:
-1
๐ก Note:
The target value 6 does not exist in the array. Since the array is sorted and 6 would be between 5 and 7, we can determine it's missing during the binary search phase.
example_3.py โ Single Element Array
$
Input:
secret = [1], target = 1
โบ
Output:
0
๐ก Note:
Edge case with a single element array. The target 1 is found immediately at index 0. The boundary detection stops at position 1, and binary search finds it at index 0.
Constraints
- 1 โค secret.length โค 104
- -104 โค secret[i], target โค 104
- secret is sorted in strictly increasing order
- You must write an algorithm with O(log n) runtime complexity
Visualization
Tap to expand
Understanding the Visualization
1
Exponential Exploration
Use your flashlight to check positions 1, 2, 4, 8, 16... doubling each time until you hit the dark area (boundary)
2
Establish Search Zone
Now you know the shelf ends somewhere between the last lit position and the dark area - this becomes your search range
3
Binary Search
Within this range, use binary search - check the middle, then eliminate half the remaining area based on what you find
4
Locate Target
Continue halving the search space until you find your target book or determine it doesn't exist
Key Takeaway
๐ฏ Key Insight: By exponentially finding the boundary and then binary searching, we achieve O(log n) complexity even with an unknown array size!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code