Binary Searchable Numbers in an Unsorted Array - Problem

Consider a function that implements an algorithm similar to Binary Search. The function has two input parameters: sequence is a sequence of integers, and target is an integer value. The purpose of the function is to find if the target exists in the sequence.

The pseudocode of the function is as follows:

func(sequence, target)
  while sequence is not empty
    randomly choose an element from sequence as the pivot
    if pivot = target, return true
    else if pivot < target, remove pivot and all elements to its left from the sequence
    else, remove pivot and all elements to its right from the sequence
  end while
  return false

When the sequence is sorted, the function works correctly for all values. When the sequence is not sorted, the function does not work for all values, but may still work for some values.

Given an integer array nums, representing the sequence, that contains unique numbers and may or may not be sorted, return the number of values that are guaranteed to be found using the function, for every possible pivot selection.

Input & Output

Example 1 — Basic Unsorted Array
$ Input: nums = [1,3,4,2]
Output: 1
💡 Note: Only element 3 at index 1 is binary searchable. It's greater than the max element to its left (1) and there are complex relationships with elements to the right, but through careful analysis, only 1 element satisfies the binary search property.
Example 2 — Sorted Array
$ Input: nums = [1,2,3,4,5]
Output: 5
💡 Note: In a fully sorted array, every element is binary searchable because the binary search algorithm works correctly for all elements regardless of pivot selection.
Example 3 — Reverse Sorted
$ Input: nums = [5,4,3,2,1]
Output: 1
💡 Note: In a reverse sorted array, typically only one element (often the middle one) can be reliably found through the modified binary search process.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109
  • All elements in nums are unique

Visualization

Tap to expand
INPUT ARRAYALGORITHM STEPSFINAL RESULT1342idx 0idx 1idx 2idx 3Array: [1,3,4,2]Unique integersNot sorted1Compute leftMax array2Compute rightMin array3Check: leftMax < num < rightMin4Count valid elementsleftMax: [-∞, 1, 3, 4]rightMin: [2, 2, 2, ∞]Element 3: 1 < 3, but 3 > 2Only specific elements work1SearchableBinary searchable countOut of 4 total elementsOnly 1 element satisfiesthe search conditionsKey Insight:An element is binary searchable if it maintains correct relative position:greater than left maximum AND smaller than right minimumTutorialsPoint - Binary Searchable Numbers | Optimal Left/Right Analysis
Asked in
Google 25 Amazon 20 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen