Binary Searchable Numbers in an Unsorted Array - Problem
Given an integer array nums with unique elements that may or may not be sorted, determine how many numbers are guaranteed to be found by a modified binary search algorithm.
The algorithm works as follows:
- Randomly select a pivot element from the remaining sequence
- 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 sequence is empty or target is found
A number is binary searchable if it can be found regardless of which pivot is chosen at each step. Return the count of such numbers.
Input & Output
Example 1 — Mixed Array
$
Input:
nums = [1, 3, 2, 4, 5]
›
Output:
3
💡 Note:
Numbers 1, 4, and 5 are binary searchable. Number 1 is the minimum, so it will always be found. Number 4 is greater than all elements to its left (1, 3, 2) and smaller than elements to its right (5). Number 5 is the maximum, so it will always be found. Numbers 3 and 2 are not binary searchable because they don't maintain the required ordering property.
Example 2 — Already Sorted
$
Input:
nums = [1, 2, 3, 4, 5]
›
Output:
5
💡 Note:
When the array is already sorted, all elements are binary searchable because each element is greater than all elements to its left and smaller than all elements to its right, which guarantees the modified binary search will find them regardless of pivot selection.
Example 3 — Reverse Sorted
$
Input:
nums = [5, 4, 3, 2, 1]
›
Output:
1
💡 Note:
In a reverse sorted array, only the minimum element (1) is binary searchable. Since 1 is smaller than all other elements, any pivot selection will eventually eliminate all larger elements, leaving 1 to be found.
Constraints
- 1 ≤ nums.length ≤ 105
- -109 ≤ nums[i] ≤ 109
- All elements in nums are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Unsorted array with unique elements
2
Analyze Positions
Check max-left and min-right conditions for each element
3
Count Searchable
Elements that satisfy the binary search property
Key Takeaway
🎯 Key Insight: Elements are binary searchable when they maintain proper ordering relative to their neighbors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code