The "Count Hills and Valleys" coding problem involves identifying specific peaks and troughs in an array. A "hill" is an index (or a group of adjacent equal indices) where the neighboring non-equal elements on both sides are smaller. Conversely, a "valley" is where both neighboring non-equal elements are larger. The problem explicitly tells you to ignore adjacent duplicates when determining the "neighbors."
This is a popular "Easy" question at companies like Meta and Google because it tests edge-case handling and the ability to simplify data. The trick lies in how you handle sequences of identical numbers. It evaluates whether you can "compress" the input or use a smart traversal to skip redundant information while maintaining the relative structure of the array.
The most effective pattern here is Array Compression or Data Sanitization. By first removing all adjacent duplicates from the array, you turn a complex problem with plateaus into a simple one where every element is different from its neighbor. After compression, you simply iterate through the new array and check if an element is greater than both its neighbors (hill) or smaller than both (valley).
Take the array nums = [2, 4, 1, 1, 6, 5].
[2, 4, 1, 6, 5].Many candidates fail to handle the "plateau" case correctly—for example, treating a sequence like [1, 2, 2, 1] as two hills instead of one. Others might struggle with index boundaries, trying to check neighbors for the first or last elements of the array, which cannot be hills or valleys by definition.
When a problem asks you to ignore duplicates or handle sequences as single units, think about "preprocessing" the data. Reducing the input size or simplifying its properties before running your main logic often makes the solution much cleaner and less prone to bugs.