Count Hills and Valleys in an Array (LeetCode 2210): Solution and Explanation
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
- Set
count = 0andleft = nums[0]. - For
ifrom 1 to n - 2, skip the index ifnums[i] == nums[i + 1], since the run continues. - Otherwise, add one to
countifnums[i]is greater than bothleftandnums[i + 1], or less than both. - Set
left = nums[i], because the run ending atiis now the nearest different value for what comes next. Returncount.
Step-by-step example
nums = [2,4,1,1,6,5]
- left = 2. At i = 1, 4 is above both 2 and 1, so it is a hill. count = 1, left = 4.
- At i = 2, nums[2] equals nums[3], so the run of 1s continues. Skip.
- At i = 3, 1 is below both left = 4 and 6, so the run is a valley. count = 2, left = 1.
- 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 count1class Solution {
2 public int countHillValley(int[] nums) {
3 int count = 0;
4 int left = nums[0];
5 for (int i = 1; i < nums.length - 1; i++) {
6 if (nums[i] == nums[i + 1]) {
7 continue;
8 }
9 if ((nums[i] > left && nums[i] > nums[i + 1]) || (nums[i] < left && nums[i] < nums[i + 1])) {
10 count++;
11 }
12 left = nums[i];
13 }
14 return count;
15 }
16}1class Solution {
2public:
3 int countHillValley(vector<int>& nums) {
4 int count = 0;
5 int left = nums[0];
6 for (int i = 1; i + 1 < (int)nums.size(); i++) {
7 if (nums[i] == nums[i + 1]) {
8 continue;
9 }
10 if ((nums[i] > left && nums[i] > nums[i + 1]) || (nums[i] < left && nums[i] < nums[i + 1])) {
11 count++;
12 }
13 left = nums[i];
14 }
15 return count;
16 }
17};Time and space complexity
O(n)
Each index is visited once with constant work.
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 plateaunums[i - 1]equalsnums[i]and hides the real neighbour. - Updating
lefton 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.