KatInterview

Find Peak Positions in an Integer Sequence

Arrays & HashingAuto-graded · 21 test cases
EasyAuto-gradedArrays & Hashingarraystraversalboundary-conditions

Last updated

Scan an integer list and return the indices of elements strictly larger than every neighbor that exists, handling the ends, plateaus, and tiny inputs correctly.

Find Peak Positions

You are given a list of integers values. Return the position of every peak in the list, in increasing order of index.

A position i is a peak when the value there is strictly greater than each of its adjacent values that actually exist:

  • For an interior position, values[i] must be strictly greater than both values[i - 1] and values[i + 1].
  • For the first position, only the right neighbor exists, so values[0] must be strictly greater than values[1].
  • For the last position, only the left neighbor exists, so the last value must be strictly greater than the one before it.
  • If the list has exactly one element, that element has no neighbors and its position 0 counts as a peak.
  • If the list is empty, return an empty list.

Because the comparison is strict, equal adjacent values never form a peak. For example, in a flat stretch such as [1, 3, 3, 1], neither 3 qualifies.

Task

Implement find_peak_positions(values) that returns a list of the indices of all peaks, sorted ascending.

Constraints

  • 0 <= len(values) <= 10^5
  • Each element is an integer.
  • The returned list must contain indices (not values) in ascending order.
  • An O(n) solution is expected.

Examples

Example 1

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

Output: [1, 3]

Hints

Hint 1

Think about what each index needs to know: only the values immediately to its left and right.

Hint 2

Treat a missing neighbor as automatically satisfying the condition, so the first and last positions need no separate branch if you write the check carefully.

Hint 3

Use short-circuit logic such as `i == 0 or values[i] > values[i - 1]` so you never read outside the list, and remember a one-element list yields `[0]` while an empty list yields `[]`.