Skip to main content
Back to problems
#1966
Medium Algorithms

Binary searchable numbers in an unsorted array

Array Binary Search Stack Monotonic Stack
63.6% acceptance
Mar 31, 2026
80
13
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn binary_searchable_numbers(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    // A number nums[i] is searchable iff:
    // - All elements to its left are smaller than it (prefix max <= nums[i])
    // - All elements to its right are larger than it (suffix min >= nums[i])
    let mut prefix_max = vec![i32::MIN; n];
    let mut suffix_min = vec![i32::MAX; n];
    
    prefix_max[0] = nums[0];
    for i in 1..n {
      prefix_max[i] = prefix_max[i - 1].max(nums[i]);
    }
    
    suffix_min[n - 1] = nums[n - 1];
    for i in (0..n - 1).rev() {
      suffix_min[i] = suffix_min[i + 1].min(nums[i]);
    }
    
    let mut count = 0;
    for i in 0..n {
      if prefix_max[i] <= nums[i] && suffix_min[i] >= nums[i] {
        count += 1;
      }
    }
    count
  }
}