Leetcode #702: Search in a Sorted Array of Unknown Size
In this guide, we solve Leetcode #702 Search in a Sorted Array of Unknown Size in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
This is an interactive problem. You have a sorted array of unique elements and an unknown size.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Array, Binary Search, Interactive
Intuition
The problem structure suggests a monotonic decision, which makes binary search a natural fit.
By halving the search space each step, we reach the answer efficiently.
Approach
Search either directly on a sorted array or on the answer space using a check function.
Each check is fast, and the logarithmic search keeps the overall runtime low.
Steps:
- Define the search bounds.
- Check the mid point condition.
- Narrow the bounds until convergence.
Example
Input: secret = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in secret and its index is 4.
Python Solution
# """
# This is ArrayReader's API interface.
# You should not implement it, or speculate about its implementation
# """
# class ArrayReader:
# def get(self, index: int) -> int:
class Solution:
def search(self, reader: "ArrayReader", target: int) -> int:
r = 1
while reader.get(r) < target:
r <<= 1
l = r >> 1
while l < r:
mid = (l + r) >> 1
if reader.get(mid) >= target:
r = mid
else:
l = mid + 1
return l if reader.get(l) == target else -1
Complexity
The time complexity is , where is the position of the target value. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.