Skip to main content
LeetCode 1966, Medium. Topics: Array, Binary Search, Stack, Monotonic Stack. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 27 parametrized pytest cases, and a playground notebook:

Problem

<p>Consider a function that implements an algorithm <strong>similar</strong> to <a href=“https://leetcode.com/explore/learn/card/binary-search/” target=“_blank”>Binary Search</a>. The function has two input parameters: <code>sequence</code> is a sequence of integers, and <code>target</code> is an integer value. The purpose of the function is to find if the <code>target</code> exists in the <code>sequence</code>.</p> <p>The pseudocode of the function is as follows:</p> <pre> func(sequence, target) while sequence is not empty <strong>randomly</strong> choose an element from sequence as the pivot if pivot = target, return <strong>true</strong> 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 <strong>false</strong> </pre> <p>When the <code>sequence</code> is sorted, the function works correctly for <strong>all</strong> values. When the <code>sequence</code> is not sorted, the function does not work for all values, but may still work for <strong>some</strong> values.</p> <p>Given an integer array <code>nums</code>, representing the <code>sequence</code>, that contains <strong>unique</strong> numbers and <strong>may or may not be sorted</strong>, return <em>the number of values that are <strong>guaranteed</strong> to be found using the function, for <strong>every possible</strong> pivot selection</em>.</p>

Examples

Constraints

  • 1 <= nums.length <= 10<sup>5</sup>
  • -10<sup>5</sup> <= nums[i] <= 10<sup>5</sup>
  • All the values of <code>nums</code> are <strong>unique</strong>.
<p><strong>Follow-up:</strong> If <code>nums</code> has <strong>duplicates</strong>, would you modify your algorithm? If so, how?</p>

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026