KatInterview

Earliest Strict Valley in an Integer Sequence

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingarrayscanboundary-conditions

Last updated

Scan an integer list for the leftmost interior value strictly smaller than both adjacent values, returning -1 if none exists, which tests boundary handling and strict comparisons.

You are given a list of non-negative integers. A valley is an element that is strictly smaller than the element directly before it and also strictly smaller than the element directly after it.

Find the valley that appears earliest in the list (lowest index) and return its value.

Function

Implement first_valley(values), where values is a list of integers. It returns a single integer.

Rules

  • Only elements that have both a left and a right neighbor can be valleys. That means the first and last elements are never valleys.
  • An element at index i is a valley only if values[i - 1] > values[i] and values[i + 1] > values[i]. A neighbor that is merely equal to the element does not count as larger.
  • If several valleys exist, choose the one with the smallest index (not the one with the smallest value) and return its value.
  • If no valley exists, return -1. This also applies when the list has fewer than 3 elements.

Constraints

  • 1 <= len(values) <= 10^5
  • 0 <= values[i] <= 10^9
  • Because every value is non-negative, a result of -1 always means "no valley found".

Examples

Example 1

Input: first_valley([5, 3, 4, 1, 2])

Output: 3

Example 2

Input: first_valley([2, 2, 7, 6, 9, 0])

Output: 6

Example 3

Input: first_valley([1, 2, 2, 3])

Output: -1

Hints

Hint 1

Which indices can possibly have both a left and a right neighbor? Restrict your loop to those.

Hint 2

Use strict comparisons on both sides: an equal neighbor must cause the element to be rejected.

Hint 3

You want the earliest valley by position, so return as soon as you find one instead of collecting them all. Return the value, not the index.