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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code