Binary Searchable Numbers in an Unsorted Array — LeetCode 1966 Python Solution
- Problem
- #1966
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
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 falsePython solution
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
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
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.