Count Hills and Valleys in an Array - Problem

You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i]. Similarly, an index i is part of a valley in nums if the closest non-equal neighbors of i are larger than nums[i].

Adjacent indices i and j are part of the same hill or valley if nums[i] == nums[j].

Note that for an index to be part of a hill or valley, it must have a non-equal neighbor on both the left and right of the index.

Return the number of hills and valleys in nums.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,3,2,4,1]
Output: 3
💡 Note: Index 1 is valley (2 > 1 < 3), index 3 is valley (3 > 2 < 4), index 5 is valley (4 > 1, no right neighbor so not counted). Actually index 1, 3, and 4 form hills/valleys, so answer is 3.
Example 2 — Equal Adjacent Values
$ Input: nums = [6,6,5,5,4,1]
Output: 0
💡 Note: No hills or valleys exist. Adjacent equal values like 6,6 and 5,5 are treated as same elevation level.
Example 3 — Single Hill
$ Input: nums = [1,4,1]
Output: 1
💡 Note: Index 1 forms a hill since both neighbors (1,1) are smaller than 4.

Constraints

  • 3 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Count Hills and Valleys in an Array INPUT 2 1 3 2 4 1 2 1 3 2 4 1 i=0 i=1 i=2 i=3 i=4 i=5 nums = [2,1,3,2,4,1] ALGORITHM STEPS 1 Initialize prev = nums[0], count = 0 2 Iterate i from 1 to n-2 Skip equal neighbors 3 Check Hill/Valley Hill: prev < curr > next Valley: prev > curr < next 4 Update prev & count prev = curr if changed Tracking: i=1: prev=2, curr=1, next=3 Valley! i=2: prev=1, curr=3, next=2 Hill! i=4: prev=2, curr=4, next=1 Hill! count = 3 FINAL RESULT Valley Hill Hill Hill (2 found) Valley (1 found) Endpoint/Normal Output: 3 Key Insight: Track the previous non-equal value to handle plateaus (consecutive equal values). A hill has both neighbors smaller; a valley has both neighbors larger. Time: O(n) single pass | Space: O(1) constant extra space TutorialsPoint - Count Hills and Valleys in an Array | One Pass with Previous Tracking
Asked in
Google 15 Amazon 12 Meta 8
18.0K Views
Medium Frequency
~15 min Avg. Time
430 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen