Valley Finder: Binary Search on an Unsorted Zigzag Array
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Find a valley index in an array of adjacent-distinct integers in logarithmic time, using a fixed halving rule that makes the returned index deterministic.
Valley Finder: Binary Search on an Unsorted Zigzag Array
You are given a nonempty list of integers heights. An index i is a valley if heights[i] is strictly smaller than every neighbor it has. Positions beyond either end of the list count as infinitely large, so the first and last elements only need to be smaller than their single real neighbor.
No two adjacent elements are equal. The list is not sorted and may contain many valleys.
Return the index of a valley, using an iterative algorithm that runs in O(log n) time.
Which valley to return
To make the expected output unique, your function must return the index produced by the following window-shrinking procedure:
- Start with a window
[lo, hi] = [0, n - 1], wherenis the length of the list. - While
lo < hi:- Let
mid = (lo + hi) // 2(integer division, rounding down). - If
heights[mid] > heights[mid + 1], setlo = mid + 1. - Otherwise, set
hi = mid.
- Let
- Return
lo.
For example, for [1, 4, 3] both index 0 and index 2 are valleys, but this procedure gives 2, so 2 is the expected answer.
Constraints
1 <= len(heights) <= 1_000_000heights[i] != heights[i + 1]for every adjacent pair.-1_000_000_000 <= heights[i] <= 1_000_000_000- The solution must be iterative (no recursion) and run in
O(log n)time. - The returned index must match the one produced by the procedure above.
Examples
Example 1
Input: find_valley_index([9, 7, 3, 5, 8])
Output: 2
Example 2
Input: find_valley_index([1, 4, 3])
Output: 2
Example 3
Input: find_valley_index([6])
Output: 0
Hints
Hint 1
You do not need sorted data for binary search, only a rule that discards half the window while guaranteeing a valley remains in the kept half.
Hint 2
Compare heights[mid] with heights[mid + 1]. If the values fall going right, a valley must exist at or after mid + 1. If they rise, a valley must exist at or before mid.
Hint 3
Loop while lo < hi so that mid + 1 is always in range. Use lo = mid + 1 or hi = mid, never hi = mid - 1. When the loop ends, lo is the answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A linear scan would find a valley in O(n), but we need O(log n). Binary search does not require sorted input. It only requires a rule that discards half of the search window while guaranteeing that a valley remains in the half we keep.
Look at heights[mid] and heights[mid + 1]. Because adjacent values differ, exactly one case applies:
heights[mid] > heights[mid + 1](falling to the right). Walk right frommid + 1. Either the values start rising at some point, which creates a valley, or they keep falling to the last element. The last element is a valley because its missing neighbor counts as infinity. So a valley exists in[mid + 1, hi], and we setlo = mid + 1.heights[mid] < heights[mid + 1](rising to the right). By the mirrored argument, a valley exists in[lo, mid], andmiditself may be it. We sethi = mid.
When lo == hi, that index is returned.
Why it is correct
Maintain this invariant: either lo == 0 or heights[lo - 1] > heights[lo], and either hi == n - 1 or heights[hi] < heights[hi + 1]. The window is walled in by larger values, or by the boundary, which acts as infinity.
- Initially both conditions hold through the boundary cases.
- Moving
lo = mid + 1: the element left of the newloisheights[mid], which is larger, so the left wall holds. - Moving
hi = mid: the element right of the newhiisheights[mid + 1], which is larger, so the right wall holds. - At
lo == hi: both neighbors are larger or missing, which is exactly the definition of a valley.
Reading heights[mid + 1] is safe because mid < hi <= n - 1 while lo < hi. The window shrinks strictly each iteration, so the loop terminates. Fixing the exact update rule also makes the returned index deterministic when several valleys exist.
Complexity
- Time:
O(log n), since the window roughly halves every iteration. - Space:
O(1).
Reference solution
from typing import List
def find_valley_index(heights: List[int]) -> int:
lo, hi = 0, len(heights) - 1
while lo < hi:
mid = (lo + hi) // 2
if heights[mid] > heights[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo