Skip to content

2210. Count Hills and Valleys in an Array #1976

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We need to count the number of hills and valleys in an array. A hill is an index where the closest non-equal neighbors on both sides are smaller than the current element. Similarly, a valley is an index where the closest non-equal neighbors on both sides are larger than the current element. Adjacent indices with the same value are considered part of the same hill or valley.

Approach

  1. Preprocess the Array: Remove consecutive duplicates from the array. This step groups adjacent indices with the same value into a single segment, as they are considered part of the same hill or valley.
  2. Check for Hills and Valleys: Traverse the processed array (excluding the first and last elements since they l…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Jul 27, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Jul 27, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants