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.

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

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In this tutorial, we’ll see different algorithms allowing us to find the smallest missing positive integer in an array.

First, we’ll go through the explanation of the problem. After that, we’ll see three different algorithms suiting our needs. Finally, we’ll discuss their complexities.

2. Problem Explanation

First, let’s explain what the goal of the algorithm is. We want to search for the smallest missing positive integer in an array of positive integers. That is, in an array of x elements, find the smallest element between 0 and x – 1 that is not in the array. If the array contains them all, then the solution is x, the array size.

For example, let’s consider the following array: [0, 1, 3, 5, 6]. It has 5 elements. That means we’re searching for the smallest integer between 0 and 4 that is not in this array. In this specific case, it’s 2.

Now, let’s imagine another array: [0, 1, 2, 3]. As it has 4 elements, we’re searching for an integer between 0 and 3. None is missing, thus the smallest integer that is not in the array is 4.

3. Sorted Array

Now, let’s see how to find the smallest missing number in a sorted array. In a sorted array, the smallest missing integer would be the first index that doesn’t hold itself as a value.

Let’s consider the following sorted array: [0, 1, 3, 4, 6, 7]. Now, let’s see which value matches which index:

Index: 0 1 2 3 4 5
Value: 0 1 3 4 6 7

As we can see, the value index doesn’t hold integer 2, therefore 2 is the smallest missing integer in the array.

How about implementing this algorithm in Java? Let’s first create a class SmallestMissingPositiveInteger with a method searchInSortedArray():

public class SmallestMissingPositiveInteger {
    public static int searchInSortedArray(int[] input) {
        // ...
    }
}

Now, we can iterate over the array and search for the first index that doesn’t contain itself as a value and return it as the result:

for (int i = 0; i < input.length; i++) {
    if (i != input[i]) {
        return i;
    }
}

Finally, if we complete the loop without finding a missing element, we must return the next integer, which is the array length, as we start at index 0:

return input.length;

Let’s check that this all works as expected. Imagine an array of integers from 0 to 5, with the number 3 missing:

int[] input = new int[] {0, 1, 2, 4, 5};

Then, if we search for the first missing integer, 3 should be returned:

int result = SmallestMissingPositiveInteger.searchInSortedArray(input);

assertThat(result).isEqualTo(3);

But, if we search for a missing number in an array without any missing integer:

int[] input = new int[] {0, 1, 2, 3, 4, 5};

We’ll find that the first missing integer is 6, which is the length of the array:

int result = SmallestMissingPositiveInteger.searchInSortedArray(input);

assertThat(result).isEqualTo(input.length);

Next, we’ll see how to handle unsorted arrays.

4. Unsorted Array

So, what about finding the smallest missing integer in an unsorted array? There are multiple solutions. The first one is to simply sort the array first and then reuse our previous algorithm. Another approach would be to use another array to flag the integers that are present and then traverse that array to find the first one missing.

4.1. Sorting the Array First

Let’s start with the first solution and create a new searchInUnsortedArraySortingFirst() method.

So, we’ll be reusing our algorithm, but first, we need to sort our input array. In order to do that, we’ll make use of Arrays.sort():

Arrays.sort(input);

That method sorts its input according to its natural order. For integers, that means from the smallest to the greatest one. There are more details about sorting algorithms in our article on sorting arrays in Java.

After that, we can call our algorithm with the now sorted input:

return searchInSortedArray(input);

That’s it, we can now check that everything works as expected. Let’s imagine the following array with unsorted integers and missing numbers 1 and 3:

int[] input = new int[] {4, 2, 0, 5};

As 1 is the smallest missing integer, we expect it to be the result of calling our method:

int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);

assertThat(result).isEqualTo(1);

Now, let’s try it on an array with no missing number:

int[] input = new int[] {4, 5, 1, 3, 0, 2};

int result = SmallestMissingPositiveInteger.searchInUnsortedArraySortingFirst(input);

assertThat(result).isEqualTo(input.length);

That’s it, the algorithm returns 6, that is the array length.

4.2. Using a Boolean Array

Another possibility is to use another array – having the same length as the input array – that holds boolean values telling if the integer matching an index has been found in the input array or not.

First, let’s create a third method, searchInUnsortedArrayBooleanArray().

After that, let’s create the boolean array, flags, and for each integer in the input array that matches an index of the boolean array, we set the corresponding value to true:

boolean[] flags = new boolean[input.length];
for (int number : input) {
    if (number < flags.length) {
        flags[number] = true;
    }
}

Now, our flags array holds true for each integer present in the input array, and false otherwise. Then, we can iterate over the flags array and return the first index holding false. If none, we return the array length:

for (int i = 0; i < flags.length; i++) {
    if (!flags[i]) {
        return i;
    }
}

return flags.length;

Again, let’s try this algorithm with our examples. We’ll first reuse the array missing 1 and 3:

int[] input = new int[] {4, 2, 0, 5};

Then, when searching for the smallest missing integer with our new algorithm, the answer is still 1:

int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);

assertThat(result).isEqualTo(1);

And for the complete array, the answer doesn’t change either and is still 6:

int[] input = new int[] {4, 5, 1, 3, 0, 2};

int result = SmallestMissingPositiveInteger.searchInUnsortedArrayBooleanArray(input);

assertThat(result).isEqualTo(input.length);

5. Complexities

Now that we’ve covered the algorithms, let’s talk about their complexities, using Big O notation.

5.1. Sorted Array

Let’s start with the first algorithm, for which the input is already sorted. In this case, the worst-case scenario is not finding a missing integer and, therefore, traversing the entire array. This means we have linear complexity, which is noted O(n), considering is the length of our input.

5.2. Unsorted Array with Sorting Algorithm

Now, let’s consider our second algorithm. In this case, the input array is not sorted, and we sort it before applying the first algorithm. Here, the complexity will be the greatest between that of the sorting mechanism and that of the algorithm itself.

As of Java 11, the Arrays.sort() method uses a dual-pivot quick-sort algorithm to sort arrays. The complexity of this sorting algorithm is, in general, O(n log(n)), though it could degrade up to O(n²). That means the complexity of our algorithm will be O(n log(n)) in general and can also degrade up to a quadratic complexity of O(n²).

That’s for time complexity, but let’s not forget about space. Although the search algorithm doesn’t take extra space, the sorting algorithm does. Quick-sort algorithm takes up to O(log(n)) space to execute. That’s something we may want to consider when choosing an algorithm for large arrays.

5.3. Unsorted Array with Boolean Array

Finally, let’s see how our third and last algorithm performs. For this one, we don’t sort the input array, which means we don’t suffer the complexity of sorting. As a matter of fact, we only traverse two arrays, both of the same size. That means our time complexity should be O(2n), which is simplified to O(n). That’s better than the previous algorithm.

But, when it comes to space complexity, we’re creating a second array of the same size as the input. That means we have O(n) space complexity, which is worse than the previous algorithm.

Knowing all that, it’s up to us to choose an algorithm that best suits our needs, depending on the conditions in which it’ll be used.

6. Conclusion

In this article, we’ve looked at algorithms for finding the smallest missing positive integer in an array. We’ve seen how to achieve that in a sorted array, as well as in an unsorted array. We also discussed the time and space complexities of the different algorithms, allowing us to choose one wisely according to our needs.

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)