[LeetCode] Search in a Sorted Array of Unknown Size

702. Search in a Sorted Array of Unknown Size

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.

  • skip list solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* // 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 st = 0, boost = 1;
while(true) {
int n = reader.get(st);
if(n == target) return st;
else if(n > target) return -1;
else {
while(reader.get(st + boost) <= target) {
boost *= 2;
}
st += max((boost/2), 1);
boost = 1;

}
}
return -1;
}
};
  • binary search solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* // 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 l = 0, r = INT_MAX;
while(l <= r) {
int m = l + (r-l) / 2;
int n = reader.get(m);
if(n == target) return m;
else if(n > target) r = m - 1;
else l = m + 1;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/22/PS/LeetCode/search-in-a-sorted-array-of-unknown-size/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.