Problem Description
Given an unsorted array of unique integers (nums), we need to count how many values are “binary searchable”. A value is binary searchable if, when using the following modified binary search procedure (with a random pivot at each step), the search for that value is guaranteed to succeed regardless of the pivot choices made:
- While the sequence is not empty, randomly choose an element as the pivot.
- If the pivot equals the target, return true.
- If the pivot is less than the target, remove the pivot and all elements to its left.
- If the pivot is greater than the target, remove the pivot and all elements to its right.
- If the while loop finishes without finding the target, return false.
When the array is sorted, the procedure always finds the target. For an unsorted array, however, only some target values are “protected” against all bad pivot choices. We must count how many numbers in nums are guaranteed to be found regardless of how pivots are selected.
Key Insights
- For a value to be binary searchable, it must never be accidentally removed by the elimination rule no matter which pivot is chosen.
- If a candidate value at index i has any number to its left that is greater than it, then that number could be chosen as a pivot and, being greater than the candidate, remove the candidate along with everything on its right.
- Similarly, if there is any number to the right of the candidate that is smaller than it, then that number might cause the candidate’s removal.
- Thus, the candidate nums[i] is binary searchable if and only if every element to the left of it is strictly smaller and every element to the right of it is strictly larger.
- In other words, nums[i] must be the maximum value among all elements from the start up to i and the minimum value among all elements from i to the end.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution involves two passes:
- A left-to-right pass that tracks the maximum value seen so far. For each index i, we note that nums[i] is “left valid” if it is greater than all elements to its left.
- A right-to-left pass that tracks the minimum value seen so far. For each index i, nums[i] is “right valid” if it is smaller than all elements to its right.
A number is binary searchable if it satisfies both conditions:
- For index 0, the left condition is trivially true.
- For index n-1, the right condition is trivially true.
We then count all indices where both conditions hold.
In the follow-up with duplicates, the strict inequalities may need to be relaxed (or carefully handled) based on whether removal rules consider equality. One possible approach is to adjust the algorithm such that a candidate is valid only if all elements to its left are less than or equal to it and all to its right are greater than or equal to it, while also considering that duplicates might result in ambiguous removals.