Count Hills and Valleys in an Array - Problem

You are given a 0-indexed integer array nums. Your task is to count the number of hills and valleys in this array.

What is a Hill?
An index i is part of a hill if the closest non-equal neighbors on both sides are smaller than nums[i].

What is a Valley?
An index i is part of a valley if the closest non-equal neighbors on both sides are larger than nums[i].

Important Rules:

  • Adjacent equal elements belong to the same hill or valley
  • An element must have non-equal neighbors on both sides to be part of a hill or valley
  • Each hill or valley is counted as one unit, regardless of how many consecutive equal elements it contains

For example, in [2,4,1,1,6,5]:

  • Index 1 (value 4) forms a hill (neighbors 2 and 1 are both smaller)
  • Indices 2,3 (values 1,1) form one valley (neighbors 4 and 6 are both larger)
  • Index 4 (value 6) forms a hill (neighbors 1 and 5)

Return the total count of hills and valleys.

Input & Output

example_1.py โ€” Basic Hills and Valleys
$ Input: nums = [2,4,1,1,6,5]
โ€บ Output: 3
๐Ÿ’ก Note: At index 1: 4 > 2 and 4 > 1 (hill). At indices 2-3: 1 < 4 and 1 < 6 (valley, counted once). At index 4: 6 > 1 and 6 > 5 (hill). Total: 3
example_2.py โ€” All Equal Elements
$ Input: nums = [6,6,5,5,4,1]
โ€บ Output: 0
๐Ÿ’ก Note: After compression: [6,5,4,1]. This is strictly decreasing, so no element has neighbors on both sides that are smaller or larger. No hills or valleys exist.
example_3.py โ€” Single Peak
$ Input: nums = [1,4,3]
โ€บ Output: 1
๐Ÿ’ก Note: At index 1: 4 > 1 and 4 > 3, forming one hill. Total: 1

Constraints

  • 3 โ‰ค nums.length โ‰ค 100
  • 1 โ‰ค nums[i] โ‰ค 100
  • Important: Adjacent equal elements belong to the same hill or valley

Visualization

Tap to expand
Mountain Range VisualizationHill4 > 2,1Valley1 < 4,6Hill6 > 1,5241165Total: 3 formations (2 hills + 1 valley)
Understanding the Visualization
1
Survey the Terrain
Look at the elevation array [2,4,1,1,6,5]
2
Compress Plateaus
Treat consecutive equal elevations as single formations: [2,4,1,6,5]
3
Identify Peaks
Find elevations higher than both neighbors: 4 and 6 are hills
4
Identify Valleys
Find elevations lower than both neighbors: 1 is a valley
Key Takeaway
๐ŸŽฏ Key Insight: By treating consecutive equal elements as single formations and looking for local extrema, we can efficiently count hills and valleys in one pass through a compressed representation.
Asked in
Amazon 15 Meta 12 Google 8 Microsoft 6
26.7K Views
Medium Frequency
~15 min Avg. Time
890 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