![](http://www.baeldung.com/wp-content/uploads/2024/07/Java-Featured-10-1024x536.jpg)
1. Introduction
When solving data structure and algorithm (DSA) problems, counting distinct patterns in sequences can be intriguing. In our previous article, we discussed various approaches to discovering peak elements in a list of integers, with methods offering different time complexities, such as O(log n) or O(n).
In this article, we’ll tackle a popular problem involving identifying and counting hills and valleys in an array of integers. This problem is an excellent way to sharpen our skills in array traversal and condition checking in Java. We’ll explore the problem step-by-step, with a solution approach, code examples, and explanations.
2. Problem Statement
Given an array of integers, we need to identify and count all the hills and valleys.
Here’s how we define them:
- Hill: A sequence of adjacent elements where the sequence begins with a lower number, peaks with a higher number, and then ends with a lower number.
- Valley: The opposite pattern, where a sequence starts high, dips to a lower value, and rises back up.
Simply put, a hill in an array is a peak flanked by lower elements on either side, while a valley is a trough with higher elements on each side.
Moreover, we should note that adjacent indices with the same value belong to the same hill or valley.
Finally, to classify an index as part of a hill or valley, it must have non-equal neighbors on both the left and the right. This also means that we’ll focus on three indices at a time to make a hill or a valley.
2.1. Example
To better understand the idea of hills and valleys, let’s take a look at the following example.
Input array: [4, 5, 6, 5, 4, 5, 4]
Let’s go step-by-step through the array to identify hills and valleys based on our definitions.
Corner indices 0 & 6: Since the first and last indices have no left and right neighbors respectively, they can’t make any hill or valley. Hence, we’ll ignore them.
Index 1 (5): The closest non-equal neighbors of 5 are 4 (left) and 6 (right). 5 isn’t greater than both neighbors (so it’s not a hill) and not less than both neighbors (so it’s not a valley).
Index 2 (6): Its neighbors are 5 (left) and 5 (right). 6 is greater than both neighbors, so this forms a hill [5, 6, 5].
Index 3 (5): The neighbors are 6 (left) and 4 (right). Since 5 is less than 6 and greater than 4, it’s neither a hill nor a valley.
For Index 4 (4): Its neighbors are 5 (left) and 5 (right). Since 4 is less than both neighbors, it clearly forms a valley [5, 4, 5].
Index 5 (5): The neighbors are 4 (left) and 4 (right). 5 is greater than both neighbors, so this forms another hill [4, 5, 4].
So, our output for the array [4, 5, 6, 5, 4, 5, 4] should be 3.
2.2. Graphical Representation
Let’s plot our array numbers, [4, 5, 6, 5, 4, 5, 4], on a graph showing hills and valleys where the x-axis represents the indices, and the y-axis shows the values at each index. We’ll connect the points with dotted lines to visually represent the hills and valleys:
![Hills and valleys in an integer array](http://www.baeldung.com/wp-content/uploads/2024/12/GraphShowingHillsValleys-1.jpg)
The green markers indicate “hills,” where a value is higher than both of its neighboring points and the red markers indicate “valleys,” where a value is lower than both of its neighbors.
The graph clearly shows that we have two hills and one valley.
3. Algorithm
Let’s define an algorithm to identify and count all hills and valleys in a given array to solve this problem:
1. Accept an array of integers, let's call it numbers.
2. Loop through numbers from the second element to the second-to-last element.
3. For each element at index i:
Let prev be numbers[i-1], current be numbers[i], and next be numbers[i+1].
4. When consecutive equal elements are encountered, skip over them while maintaining the last seen value.
5. Identify Hills:
If current is greater than both prev and next, it's a hill.
Increment hill count.
6. Identify Valleys:
If current is less than both prev and next, it's a valley.
Increment valley count.
7. Repeat Steps 3–6 until the end of the array.
8. Return the sum of hills and valley.
Thus, we can efficiently detect all the hills and valleys using this algorithm. Let’s note that we only require a single pass through the numbers array.
4. Implementation
Now, let’s implement this algorithm in Java:
int countHillsAndValleys(int[] numbers) {
int hills = 0;
int valleys = 0;
for (int i = 1; i < numbers.length - 1; i++) {
int prev = numbers[i - 1];
int current = numbers[i];
int next = numbers[i + 1];
while (i < numbers.length - 1 && numbers[i] == numbers[i + 1]) {
// skip consecutive duplicate elements
i++;
}
if (i != numbers.length - 1) {
// update the next value to the first distinct neighbor only if it exists
next = numbers[i + 1];
}
if (current > prev && current > next) {
hills++;
} else if (current < prev && current < next) {
valleys++;
}
}
return hills + valleys;
}
Here, in the countHillsAndValleys() method, we effectively identify and count hills and valleys in a given integer array. At first, we iterate through the array indices starting from the second element and ending at the second last. This ensures that each element we check has both left and right neighbors.
Next, for each index, we skip consecutive duplicate elements to avoid redundant checks and ensure the logic applies accurately to grouped elements surrounded by neighbors.
For each remaining index, we then compare the current element with its neighbors – if it’s greater than both, we recognize it as a hill; if it’s smaller than both, we identify it as a valley.
Finally, we return the total count of hills and valleys. Overall, this approach lets us optimize the performance by avoiding extra lists and memory usage, making our solution efficient and straightforward.
5. Testing Our Solution
Let’s test our logic and address various test cases by passing different arrays to countHillsAndValleys():
// Test case 1: Our example array
int[] array1 = { 4, 5, 6, 5, 4, 5, 4};
assertEquals(3, countHillsAndValleys(array1));
// Test case 2: Array with strictly increasing elements
int[] array2 = { 1, 2, 3, 4, 5, 6 };
assertEquals(0, countHillsAndValleys(array2));
// Test case 3: Constant array
int[] array3 = { 5, 5, 5, 5, 5 };
assertEquals(0, countHillsAndValleys(array3));
// Test case 4: Array with no hills or valleys
int[] array4 = { 6, 6, 5, 5, 4, 1 };
assertEquals(0, countHillsAndValleys(array4));
// Test case 5: Array with a flatten valley
int[] array5 = { 6, 5, 4, 4, 4, 5, 6 };
assertEquals(1, countHillsAndValleys(array5));
// Test case 6: Array with a flatten hill
int[] array6 = { 1, 2, 4, 4, 4, 2, 1 };
assertEquals(1, countHillsAndValleys(array6));
Here, array2 is a strictly increasing array, so it lacks any hills or valleys. Similarly, array3 is a constant array with the same element, hence it has no hills or valleys.
6. Complexity Analysis
Let’s analyze the time and space complexity of our solution:
Time Complexity: O(n), where n is the length of the array. The function countHillsAndValleys() iterates through the array once, checking each element only once.
Space Complexity: O(1), as we only use a fixed amount of space for the counters and don’t require any additional data structures.
7. Conclusion
In this tutorial, we explored a structured approach to count hills and valleys in an array using Java. Additionally, we addressed edge cases and verified the solution with various test cases.
As always, the source code for the article is available over on GitHub.