Problem Description
Given an array of integers, the task is to count the number of hills and valleys in the array. An index is considered part of a hill if its closest non-equal left and right neighbors are both less than the element at that index. Similarly, an index is part of a valley if its closest non-equal left and right neighbors are both greater than it. Consecutive indices with equal values form one hill or valley group. Note that an index must have non-equal neighbors on both sides to be counted as either.
Key Insights
- Removing consecutive duplicates simplifies the problem because repeated elements belong to the same hill or valley.
- After deduplication, only indices with both a left and right neighbor need to be evaluated.
- For each candidate index, compare it with its immediate neighbors to decide if it forms a hill (greater than both neighbors) or a valley (less than both neighbors).
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input array, due to the linear scan for deduplication and evaluation. Space Complexity: O(n) in the worst case, for storing the deduplicated array.
Solution
The solution first deduplicates the input array to collapse contiguous groups of equal numbers into one representative element. This is important because multiple adjacent equal elements should only count as one potential hill or valley.
Next, we traverse the deduplicated list starting from the second element and ending at the second-to-last element to ensure that each element considered has both a left and right neighbor. For each such element, we compare it with its immediate neighbors:
- If the element is greater than both neighbors, it is part of a hill.
- If it is less than both neighbors, it is part of a valley.
Finally, we count the number of hills and valleys found.