786. Search in a Sorted Array of Unknown Size
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to find a target value in a sorted array of unknown size. We can only access the array through an ArrayReader interface. A standard binary search is not directly applicable because we don't know the right boundary (i.e., the array's size). The key constraints are that the array is sorted, contains unique elements, and the solution must have a time complexity of O(log n), where n is the array's size.
Solution
Search in a Sorted Array of Unknown Size in Python
# """
# 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:
# Phase 1: Find the search bounds [left, right]
left, right = 0, 1
# Expand the search space exponentially.
# reader.get(right) will return a large value (2**31 - 1) for out-of-bounds access,
# which is guaranteed to be greater than the target by problem constraints.
while reader.get(right) < target:
left = right
right *= 2
# Phase 2: Perform binary search within the found bounds [left, right]
while left <= right:
mid = left + (right - left) // 2
val = reader.get(mid)
if val == target:
return mid # Target found
elif val > target:
# This condition also handles the out-of-bounds case implicitly.
right = mid - 1 # Search in the left half
else: # val < target
left = mid + 1 # Search in the right half
# Target not found
return -1
Search in a Sorted Array of Unknown Size in Java
/**
* // This is ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* interface ArrayReader {
* public int get(int index) {}
* }
*/
class Solution {
public int search(ArrayReader reader, int target) {
// Phase 1: Find the search bounds [left, right]
int left = 0, right = 1;
// Expand the search space exponentially.
// reader.get(right) will return Integer.MAX_VALUE for out-of-bounds access,
// which is guaranteed to be greater than the target by problem constraints.
while (reader.get(right) < target) {
left = right;
right *= 2;
}
// Phase 2: Perform binary search within the found bounds [left, right]
while (left <= right) {
int mid = left + (right - left) / 2;
int val = reader.get(mid);
if (val == target) {
return mid; // Target found
} else if (val > target) {
// This condition also handles the out-of-bounds case, as the returned
// value (Integer.MAX_VALUE) will be greater than the target.
right = mid - 1; // Search in the left half
} else { // val < target
left = mid + 1; // Search in the right half
}
}
// Target not found
return -1;
}
}
Search in a Sorted Array of Unknown Size in C++
/**
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* class ArrayReader {
* public:
* int get(int index);
* };
*/
class Solution {
public:
int search(const ArrayReader& reader, int target) {
// Phase 1: Find the search bounds [left, right]
int left = 0, right = 1;
// Expand the search space exponentially until reader.get(right) >= target.
// The problem guarantees the out-of-bounds value (2^31 - 1) is larger than any target,
// so this loop will terminate even if target is larger than all elements.
while (reader.get(right) < target) {
left = right;
// Double the right boundary. The problem constraints (size <= 10^4)
// prevent this from overflowing a standard 32-bit integer.
right *= 2;
}
// Phase 2: Perform binary search within the found bounds [left, right]
while (left <= right) {
// Use `left + (right - left) / 2` to prevent potential overflow.
int mid = left + (right - left) / 2;
int val = reader.get(mid);
if (val == target) {
return mid; // Target found
} else if (val > target) { // This also handles out-of-bounds values implicitly
right = mid - 1; // Search in the left half
} else { // val < target
left = mid + 1; // Search in the right half
}
}
// Target not found
return -1;
}
};
Search in a Sorted Array of Unknown Size in TypeScript
/**
* class ArrayReader {
* // This is the ArrayReader's API interface.
* // You should not implement it, or speculate about its implementation
* get(index: number): number {};
* };
*/
function search(reader: ArrayReader, target: number): number {
// Phase 1: Find the search bounds [left, right]
let left = 0;
let right = 1;
// Expand the search space exponentially.
// reader.get(right) will return a large value for out-of-bounds access,
// which is guaranteed to be greater than the target by problem constraints.
while (reader.get(right) < target) {
left = right;
right *= 2;
}
// Phase 2: Perform binary search within the found bounds [left, right]
while (left <= right) {
// Use Math.floor for integer division in JavaScript/TypeScript.
const mid = left + Math.floor((right - left) / 2);
const val = reader.get(mid);
if (val === target) {
return mid; // Target found
} else if (val > target) {
// This condition also handles the out-of-bounds case implicitly.
right = mid - 1; // Search in the left half
} else { // val < target
left = mid + 1; // Search in the right half
}
}
// Target not found
return -1;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.