eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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

 

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)