How can you perform binary search on a sorted array of infinite or unknown length (when the count function is unavailable)?
Asked at
AI answer
Use exponential search to find the bounds, then run a standard binary search within them. Start at index 0 and double the index (1, 2, 4, 8, ...) while the value there is less than the target. This finds an interval containing the target. Then perform a binary search within that interval.
If the array is actually finite but its length is unknown, an access beyond its bounds must be recognized as the end of the data—for example, as a special read result. Without a way to determine that an index is invalid or to check the value at an index, the problem cannot be solved.
The complexity is O(log i), where i is the position of the target element; the extra space is O(1). To find the first occurrence when there are duplicates, continue the binary search to the left after finding a match.
Also asked at Astrum Entertainment
- What is the difference between the equality operator '==' and the strict equality operator '===' in PHP?
- Why is rounding (floor) used when calculating the midpoint, what other ways are there to remove the fractional part in PHP, and which is more optimized (the difference between a function and a language construct)?
- Implement a weighted Round Robin algorithm (distributing requests across arrays according to their weights, for example 30%, 50%, 20%).
- Implement binary search on a sorted array.
- What should a binary search function return if the target element is not found: -1 or an exception? Which is more appropriate?
Similar questions
- What will be the output when array_search() is used in an if condition?
- What is the time and space complexity of your implementation?
- What is a B-tree?
- How can you make the second part of the previous problem produce 3, without using return or passing an object?
- What if we needed to reverse a string containing Cyrillic characters? Would this implementation work, and what would need to change?