Problem Statement
Given a sorted array of unknown size, find the element at a given index.
You have a sorted array of unique elements and an unknown size. You do not have direct 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
2^31 - 1
if 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.
Example 1
Input: secret = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in secret
and its index is 4.
Example 2
Input: secret = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in secret
so return -1.
Approach 1: Brute Force
Idea
Iterate over the array starting from index 0 and check each element until we find the target
or reach the end of the array.
Steps
- Start from index
i = 0
.
- Access
ArrayReader.get(i)
.
- If the value is equal to the
target
, return i
.
- If
ArrayReader.get(i)
returns 2^31 - 1
, stop as we've reached out of bounds.
- Continue this until the target is found or the end is reached.
Time Complexity
- O(n), where
n
is the length of the array up to the target or end.
Space Complexity
Example Code
Dry Run
secret = [-1, 0, 3, 5, 9, 12]
, target = 9
- Start with
i = 0
, reader.get(i) = -1
, not target.
- Increment
i
. Check reader.get(1) = 0
.
- Increment
i
until reader.get(4) = 9
, return i = 4
.
Approach 2: Efficient Approach (Binary Search)
Idea
Since the array is sorted, use a modified binary search approach to handle unknown size.
Steps
- Start with
left = 0
and right = 1
.
- Increase
right
exponentially until ArrayReader.get(right)
exceeds the target
or returns 2^31 - 1
.
- Perform binary search between
left
and right
to find the target
.
Time Complexity
Space Complexity
Example Code
Dry Run
secret = [-1, 0, 3, 5, 9, 12]
, target = 9
- Start with
left = 0
, right = 1
.
- Increase
right
until reader.get(right) >= 9
.
- Binary search within
[left, right]
finds target
at index 4
.
Complexity Analysis
Brute Force Approach
- Time Complexity: O(n)
- Space Complexity: O(1)
Efficient Approach
- Time Complexity: O(log n)
- Space Complexity: O(1)
Conclusion
The brute force approach works but is inefficient for large arrays. The efficient approach using binary search drastically reduces time complexity to O(log n) by leveraging the sorted nature of the array, making it more suitable for real-world applications with unknown array sizes.