Skip to main content
Back to problems
#702
Medium Algorithms

Search in a sorted array of unknown size

Array Binary Search Interactive
73.1% acceptance
Mar 31, 2026
941
51
This is an interactive problem. You have a sorted array of unique elements and an unknown size. You do not have an access to the array but you can use the ArrayReader interface to access it. You can call ArrayReader.get(i) that: returns the value at the ith index (0-indexed) of the secret array (i.e., secret[i]), or returns 231 - 1 if the i is out of the boundary of the array. You are also given an integer target. Return the index k of the hidden array where secret[k] == target or return -1 otherwise. You must write an algorithm with O(log n) runtime complexity.

Solution

C++
Time O(n)
Space O(1)
LeetCode
solution.cpp
/**
 * // 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) {
    int hi = 1;
    while (reader.get(hi) < target) hi *= 2;
    int lo = hi / 2;
    while (lo <= hi) {
      int mid = lo + (hi - lo) / 2;
      int val = reader.get(mid);
      if (val == target) return mid;
      else if (val < target) lo = mid + 1;
      else hi = mid - 1;
    }
    return -1;
  }
};