Binary Searchable Numbers in an Unsorted Array
Imagine you have a modified binary search algorithm that works on unsorted arrays by randomly selecting pivots instead of always choosing the middle element. While this algorithm doesn't guarantee to find all values in an unsorted array, some values are guaranteed to be found regardless of which pivots are randomly selected.
Given an integer array nums with unique numbers (which may or may not be sorted), your task is to determine how many values are guaranteed to be found using this modified binary search, no matter which pivots are randomly chosen during the search process.
The Algorithm:
- Start with the entire array
- Randomly pick any element as pivot
- If pivot equals target, return
true - If pivot < target, remove pivot and all elements to its left
- If pivot > target, remove pivot and all elements to its right
- Repeat until array is empty or target is found
A number is binary searchable if it will always be found regardless of the random pivot selections made during the search.
Input & Output
Visualization
Time & Space Complexity
For each of n elements, we check all elements to its left and right in worst case
Only using constant extra space for variables
Constraints
- 1 โค nums.length โค 103
- -104 โค nums[i] โค 104
- All elements in nums are unique