KatInterview

Valley Finder: Binary Search on an Unsorted Zigzag Array

Heaps, Sorting & SearchAuto-graded · 21 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraysinvariants

Last 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:

  1. Start with a window [lo, hi] = [0, n - 1], where n is the length of the list.
  2. While lo < hi:
    • Let mid = (lo + hi) // 2 (integer division, rounding down).
    • If heights[mid] > heights[mid + 1], set lo = mid + 1.
    • Otherwise, set hi = mid.
  3. 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_000
  • heights[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.