MediumNo. 1966LeetCode Premium

Binary Searchable Numbers in an Unsorted Array — LeetCode 1966 Python Solution

Topics
Array, Binary Search
Reading time
3 min

The 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.

Example

Example
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

Python solution

PythonSolution
class Solution:
    def binarySearchableNumbers(self, nums: List[int]) -> int:
        n = len(nums)
        ok = [1] * n
        mx, mi = -1000000, 1000000
        for i, x in enumerate(nums):
            if x < mx:
                ok[i] = 0
            else:
                mx = x
        for i in range(n - 1, -1, -1):
            if nums[i] > mi:
                ok[i] = 0
            else:
                mi = nums[i]
        return sum(ok)

Complexity

Time
O(log n) or O(n log n)
Space · auxiliary
O(1)

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1966. Binary Searchable Numbers in an Unsorted Array is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1966. Binary Searchable Numbers in an Unsorted Array?

LeetCode 1966. Binary Searchable Numbers in an Unsorted Array is rated Medium on LeetCode.

What topics does LeetCode 1966. Binary Searchable Numbers in an Unsorted Array cover?

LeetCode 1966. Binary Searchable Numbers in an Unsorted Array is tagged Array and Binary Search on LeetCode.

Is LeetCode 1966. Binary Searchable Numbers in an Unsorted Array a premium problem?

Yes. LeetCode 1966. Binary Searchable Numbers in an Unsorted Array is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.