Count Hills and Valleys in an Array (LeetCode 2210): Solution and Explanation

Easy
Array

Count the peaks and dips in an array, where a run of equal values counts as a single peak or dip and both ends of the array never count.

Intuition

Draw the array as a landscape. A hill is a spot higher than the ground on both sides, a valley is a spot lower than both sides.

The catch is flat ground. In [2,1,1,1,2] the three 1s form one valley, not three. So a run of equal values should be judged once, and its neighbours are the nearest values that differ from it.

Judge each run at its last index. There, the right neighbour nums[i + 1] is already different. For the left side, remember left, the value of the previous run, which is updated only when a run ends.

Approach: One pass with a left anchor

  1. Set count = 0 and left = nums[0].
  2. For i from 1 to n - 2, skip the index if nums[i] == nums[i + 1], since the run continues.
  3. Otherwise, add one to count if nums[i] is greater than both left and nums[i + 1], or less than both.
  4. Set left = nums[i], because the run ending at i is now the nearest different value for what comes next. Return count.

Step-by-step example

nums = [2,4,1,1,6,5]
  1. left = 2. At i = 1, 4 is above both 2 and 1, so it is a hill. count = 1, left = 4.
  2. At i = 2, nums[2] equals nums[3], so the run of 1s continues. Skip.
  3. At i = 3, 1 is below both left = 4 and 6, so the run is a valley. count = 2, left = 1.
  4. At i = 4, 6 is above both 1 and 5, a hill. count = 3. Index 5 is the end and never counts. Return 3.

Code: Python, Java, C++

1class Solution:
2    def countHillValley(self, nums: List[int]) -> int:
3        count = 0
4        left = nums[0]
5        for i in range(1, len(nums) - 1):
6            if nums[i] == nums[i + 1]:
7                continue
8            if (nums[i] > left and nums[i] > nums[i + 1]) or (nums[i] < left and nums[i] < nums[i + 1]):
9                count += 1
10            left = nums[i]
11        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is visited once with constant work.

Space

O(1)

Only the counter and the left anchor are stored.

Other approaches

Remove adjacent duplicates first (time O(n), space O(n))

Compress the array so no two neighbours are equal, then count every interior index that is strictly above or below both neighbours. Easy to reason about but builds a second array.

Search both directions for each index (time O(n^2), space O(1))

For each index, walk left and right to the nearest different values and compare. Needs extra care not to count a run several times, and can be quadratic on long plateaus.

Common mistakes

  • Counting every index of a flat run. Skip while the next value is equal so the run is judged once.
  • Comparing with nums[i - 1] instead of the last different value. On a plateau nums[i - 1] equals nums[i] and hides the real neighbour.
  • Updating left on skipped indices. It must change only when a run ends.
  • Counting the first or last index. They have no neighbour on one side.

Frequently asked questions

Why judge a plateau at its last index?

At the last index the right neighbour is already a different value, so one comparison against left and right decides the whole run.

Can a plateau at the start of the array be a valley?

No. It has no different value on its left side, so it cannot be a hill or a valley.

Is this the same as counting direction changes?

Yes. After removing equal neighbours, every hill or valley is a point where the slope switches between going up and going down.