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 Array213241ValleyHillValleyHillValleyHills are peaks (higher than neighbors), Valleys are low pointsOutput: Count = 3 (considering equal adjacent values as same level)
Understanding the Visualization
1
Input Array
Array with values representing elevation points
2
Find Patterns
Identify hills (higher than neighbors) and valleys (lower than neighbors)
3
Count Result
Return total number of hills and valleys found
Key Takeaway
🎯 Key Insight: Adjacent equal values belong to the same hill or valley, so we only need to compare with the nearest different neighbors
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