Skip to content
Related Articles
Find the smallest positive number missing from an unsorted array | Set 1
• Difficulty Level : Hard
• Last Updated : 15 Jun, 2021

You are given an unsorted array with both positive and negative elements. You have to find the smallest positive number missing from the array in O(n) time using constant extra space. You can modify the original array.

Examples

``` Input:  {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1

Input:  { 2, 3, -7, 6, 8, 1, -10, 15 }
Output: 4

Input: {1, 1, 0, -1, -2}
Output: 2```

A naive method to solve this problem is to search all positive integers, starting from 1 in the given array. We may have to search at most n+1 numbers in the given array. So this solution takes O(n^2) in worst case.

We can use sorting to solve it in lesser time complexity. We can sort the array in O(nLogn) time. Once the array is sorted, then all we need to do is a linear scan of the array. So this approach takes O(nLogn + n) time which is O(nLogn).

We can also use hashing. We can build a hash table of all positive elements in the given array. Once the hash table is built. We can look in the hash table for all positive integers, starting from 1. As soon as we find a number which is not there in hash table, we return it. This approach may take O(n) time on average, but it requires O(n) extra space.

A O(n) time and O(1) extra space solution:
The idea is similar to this post. We use array elements as index. To mark presence of an element x, we change the value at the index x to negative. But this approach doesn’t work if there are non-positive (-ve and 0) numbers. So we segregate positive from negative numbers as first step and then apply the approach.

Following is the two step algorithm.
1) Segregate positive numbers from others i.e., move all non-positive numbers to left side. In the following code, segregate() function does this part.
2) Now we can ignore non-positive elements and consider only the part of array which contains all positive elements. We traverse the array containing all positive numbers and to mark presence of an element x, we change the sign of value at index x to negative. We traverse the array again and print the first index which has positive value. In the following code, findMissingPositive() function does this part. Note that in findMissingPositive, we have subtracted 1 from the values as indexes start from 0 in C.

## C++

 `/* C++ program to find the``   ``smallest positive missing number */``#include ``using` `namespace` `std;` `/* Utility to swap to integers */``void` `swap(``int``* a, ``int``* b)``{``    ``int` `temp;``    ``temp = *a;``    ``*a = *b;``    ``*b = temp;``}` `/* Utility function that puts all``non-positive (0 and negative) numbers on left``side of arr[] and return count of such numbers */``int` `segregate(``int` `arr[], ``int` `size)``{``    ``int` `j = 0, i;``    ``for` `(i = 0; i < size; i++) {``        ``if` `(arr[i] <= 0) {``            ``swap(&arr[i], &arr[j]);``          ` `            ``// increment count of``            ``// non-positive integers``            ``j++;``        ``}``    ``}` `    ``return` `j;``}` `/* Find the smallest positive missing number``in an array that contains all positive integers */``int` `findMissingPositive(``int` `arr[], ``int` `size)``{``    ``int` `i;` `    ``// Mark arr[i] as visited by``    ``// making arr[arr[i] - 1] negative.``    ``// Note that 1 is subtracted``    ``// because index start``    ``// from 0 and positive numbers start from 1``    ``for` `(i = 0; i < size; i++) {``        ``if` `(``abs``(arr[i]) - 1 < size && arr[``abs``(arr[i]) - 1] > 0)``            ``arr[``abs``(arr[i]) - 1] = -arr[``abs``(arr[i]) - 1];``    ``}` `    ``// Return the first index``    ``// value at which is positive``    ``for` `(i = 0; i < size; i++)``        ``if` `(arr[i] > 0)``          ` `            ``// 1 is added because``            ``// indexes start from 0``            ``return` `i + 1;` `    ``return` `size + 1;``}` `/* Find the smallest positive missing``number in an array that contains``both positive and negative integers */``int` `findMissing(``int` `arr[], ``int` `size)``{``    ` `    ``// First separate positive``    ``// and negative numbers``    ``int` `shift = segregate(arr, size);` `    ``// Shift the array and call``    ``// findMissingPositive for``    ``// positive part``    ``return` `findMissingPositive(arr + shift,``                               ``size - shift);``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 0, 10, 2, -10, -20 };``    ``int` `arr_size = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `missing = findMissing(arr, arr_size);``    ``cout << ``"The smallest positive missing number is "` `<< missing;``    ``return` `0;``}` `// This is code is contributed by rathbhupendra`

## C

 `/* C program to find the smallest``   ``positive missing number */``#include ``#include ` `/* Utility to swap to integers */``void` `swap(``int``* a, ``int``* b)``{``    ``int` `temp;``    ``temp = *a;``    ``*a = *b;``    ``*b = temp;``}` `/* Utility function that puts all``non-positive (0 and negative) numbers on left``side of arr[] and return count of such numbers */``int` `segregate(``int` `arr[], ``int` `size)``{``    ``int` `j = 0, i;``    ``for` `(i = 0; i < size; i++) {``        ``if` `(arr[i] <= 0) {``            ``swap(&arr[i], &arr[j]);``            ``j++; ``// increment count of non-positive integers``        ``}``    ``}` `    ``return` `j;``}` `/* Find the smallest positive missing number``in an array that contains all positive integers */``int` `findMissingPositive(``int` `arr[], ``int` `size)``{``    ``int` `i;` `    ``// Mark arr[i] as visited by``    ``// making arr[arr[i] - 1] negative.``    ``// Note that 1 is subtracted``    ``// because index start``    ``// from 0 and positive numbers start from 1``    ``for` `(i = 0; i < size; i++) {``        ``if` `(``abs``(arr[i]) - 1 < size && arr[``abs``(arr[i]) - 1] > 0)``            ``arr[``abs``(arr[i]) - 1] = -arr[``abs``(arr[i]) - 1];``    ``}` `    ``// Return the first index value at which is positive``    ``for` `(i = 0; i < size; i++)``        ``if` `(arr[i] > 0)``            ``// 1 is added because indexes start from 0``            ``return` `i + 1;` `    ``return` `size + 1;``}` `/* Find the smallest positive missing``number in an array that contains``both positive and negative integers */``int` `findMissing(``int` `arr[], ``int` `size)``{``    ``// First separate positive and negative numbers``    ``int` `shift = segregate(arr, size);` `    ``// Shift the array and call findMissingPositive for``    ``// positive part``    ``return` `findMissingPositive(arr + shift, size - shift);``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 0, 10, 2, -10, -20 };``    ``int` `arr_size = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `missing = findMissing(arr, arr_size);``    ``printf``(``"The smallest positive missing number is %d "``, missing);``    ``getchar``();``    ``return` `0;``}`

## Java

 `// Java program to find the smallest``// positive missing number``import` `java.util.*;` `class` `Main {` `    ``/* Utility function that puts all non-positive``       ``(0 and negative) numbers on left side of``       ``arr[] and return count of such numbers */``    ``static` `int` `segregate(``int` `arr[], ``int` `size)``    ``{``        ``int` `j = ``0``, i;``        ``for` `(i = ``0``; i < size; i++) {``            ``if` `(arr[i] <= ``0``) {``                ``int` `temp;``                ``temp = arr[i];``                ``arr[i] = arr[j];``                ``arr[j] = temp;``                ``// increment count of non-positive``                ``// integers``                ``j++;``            ``}``        ``}` `        ``return` `j;``    ``}` `    ``/* Find the smallest positive missing``       ``number in an array that contains``       ``all positive integers */``    ``static` `int` `findMissingPositive(``int` `arr[], ``int` `size)``    ``{``        ``int` `i;` `        ``// Mark arr[i] as visited by making``        ``// arr[arr[i] - 1] negative. Note that``        ``// 1 is subtracted because index start``        ``// from 0 and positive numbers start from 1``        ``for` `(i = ``0``; i < size; i++) {``            ``int` `x = Math.abs(arr[i]);``            ``if` `(x - ``1` `< size && arr[x - ``1``] > ``0``)``                ``arr[x - ``1``] = -arr[x - ``1``];``        ``}` `        ``// Return the first index value at which``        ``// is positive``        ``for` `(i = ``0``; i < size; i++)``            ``if` `(arr[i] > ``0``)``                ``return` `i + ``1``; ``// 1 is added becuase indexes``        ``// start from 0` `        ``return` `size + ``1``;``    ``}` `    ``/* Find the smallest positive missing``       ``number in an array that contains``       ``both positive and negative integers */``    ``static` `int` `findMissing(``int` `arr[], ``int` `size)``    ``{``        ``// First separate positive and``        ``// negative numbers``        ``int` `shift = segregate(arr, size);``        ``int` `arr2[] = ``new` `int``[size - shift];``        ``int` `j = ``0``;``        ``for` `(``int` `i = shift; i < size; i++) {``            ``arr2[j] = arr[i];``            ``j++;``        ``}``        ``// Shift the array and call``        ``// findMissingPositive for``        ``// positive part``        ``return` `findMissingPositive(arr2, j);``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``0``, ``10``, ``2``, -``10``, -``20` `};``        ``int` `arr_size = arr.length;``        ``int` `missing = findMissing(arr, arr_size);``        ``System.out.println(``"The smallest positive missing number is "` `+ missing);``    ``}``}`

## Python3

 `''' Python3 program to find the``smallest positive missing number '''` `''' Utility function that puts all``non-positive (0 and negative) numbers on left``side of arr[] and return count of such numbers '''``def` `segregate(arr, size):``    ``j ``=` `0``    ``for` `i ``in` `range``(size):``        ``if` `(arr[i] <``=` `0``):``            ``arr[i], arr[j] ``=` `arr[j], arr[i]``            ``j ``+``=` `1` `# increment count of non-positive integers``    ``return` `j`  `''' Find the smallest positive missing number``in an array that contains all positive integers '''``def` `findMissingPositive(arr, size):``    ` `    ``# Mark arr[i] as visited by``    ``# making arr[arr[i] - 1] negative.``    ``# Note that 1 is subtracted``    ``# because index start``    ``# from 0 and positive numbers start from 1``    ``for` `i ``in` `range``(size):``        ``if` `(``abs``(arr[i]) ``-` `1` `< size ``and` `arr[``abs``(arr[i]) ``-` `1``] > ``0``):``            ``arr[``abs``(arr[i]) ``-` `1``] ``=` `-``arr[``abs``(arr[i]) ``-` `1``]``            ` `    ``# Return the first index value at which is positive``    ``for` `i ``in` `range``(size):``        ``if` `(arr[i] > ``0``):``            ` `            ``# 1 is added because indexes start from 0``            ``return` `i ``+` `1``    ``return` `size ``+` `1` `''' Find the smallest positive missing``number in an array that contains``both positive and negative integers '''``def` `findMissing(arr, size):``    ` `    ``# First separate positive and negative numbers``    ``shift ``=` `segregate(arr, size)``    ` `    ``# Shift the array and call findMissingPositive for``    ``# positive part``    ``return` `findMissingPositive(arr[shift:], size ``-` `shift)``    ` `# Driver code``arr ``=` `[ ``0``, ``10``, ``2``, ``-``10``, ``-``20` `]``arr_size ``=` `len``(arr)``missing ``=` `findMissing(arr, arr_size)``print``(``"The smallest positive missing number is "``, missing)` `# This code is contributed by Shubhamsingh10`

## C#

 `// C# program to find the smallest``// positive missing number``using` `System;` `class` `main {` `    ``// Utility function that puts all``    ``// non-positive (0 and negative)``    ``// numbers on left side of arr[]``    ``// and return count of such numbers``    ``static` `int` `segregate(``int``[] arr, ``int` `size)``    ``{``        ``int` `j = 0, i;``        ``for` `(i = 0; i < size; i++) {``            ``if` `(arr[i] <= 0) {``                ``int` `temp;``                ``temp = arr[i];``                ``arr[i] = arr[j];``                ``arr[j] = temp;` `                ``// increment count of non-positive``                ``// integers``                ``j++;``            ``}``        ``}` `        ``return` `j;``    ``}` `    ``// Find the smallest positive missing``    ``// number in an array that contains``    ``// all positive integers``    ``static` `int` `findMissingPositive(``int``[] arr, ``int` `size)``    ``{``        ``int` `i;` `        ``// Mark arr[i] as visited by making``        ``// arr[arr[i] - 1] negative. Note that``        ``// 1 is subtracted as index start from``        ``// 0 and positive numbers start from 1``        ``for` `(i = 0; i < size; i++) {``            ``if` `(Math.Abs(arr[i]) - 1 < size && arr[ Math.Abs(arr[i]) - 1] > 0)``                ``arr[ Math.Abs(arr[i]) - 1] = -arr[ Math.Abs(arr[i]) - 1];``        ``}` `        ``// Return the first index value at``        ``// which is positive``        ``for` `(i = 0; i < size; i++)``            ``if` `(arr[i] > 0)``                ``return` `i + 1;` `        ``// 1 is added becuase indexes``        ``// start from 0``        ``return` `size + 1;``    ``}` `    ``// Find the smallest positive``    ``// missing number in array that``    ``// contains both positive and``    ``// negative integers``    ``static` `int` `findMissing(``int``[] arr, ``int` `size)``    ``{` `        ``// First separate positive and``        ``// negative numbers``        ``int` `shift = segregate(arr, size);``        ``int``[] arr2 = ``new` `int``[size - shift];``        ``int` `j = 0;` `        ``for` `(``int` `i = shift; i < size; i++) {``            ``arr2[j] = arr[i];``            ``j++;``        ``}` `        ``// Shift the array and call``        ``// findMissingPositive for``        ``// positive part``        ``return` `findMissingPositive(arr2, j);``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] arr = { 0, 10, 2, -10, -20 };``        ``int` `arr_size = arr.Length;``        ``int` `missing = findMissing(arr, arr_size);``        ``Console.WriteLine(``"The smallest positive missing number is "` `+ missing);``    ``}``}` `// This code is contributed by Anant Agarwal.`

## Javascript

 ``
Output
`The smallest positive missing number is 1`

Note that this method modifies the original array. We can change the sign of elements in the segregated array to get the same set of elements back. But we still loose the order of elements. If we want to keep the original array as it was, then we can create a copy of the array and run this approach on the temp array.

Another approach: In this problem, we have created a list full of 0’s with size of the max() value of our given array. Now, whenever we encounter any positive value in our original array, we change the index value of our list to 1. So, after we are done, we simply iterate through our modified list, the first 0 we encounter, its (index value + 1) should be our answer since index in python starts from 0.

Below is the implementation of above approach:

## C++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;` `// Function to return the first missing positive``// number from the given unsorted array``int` `firstMissingPos(``int` `A[], ``int` `n)``{` `    ``// To mark the occurrence of elements``    ``bool` `present[n + 1] = { ``false` `};` `    ``// Mark the occurrences``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// Only mark the required elements``        ``// All non-positive elements and``        ``// the elements greater n + 1 will never``        ``// be the answer``        ``// For example, the array will be {1, 2, 3}``        ``// in the worst case and the result``        ``// will be 4 which is n + 1``        ``if` `(A[i] > 0 && A[i] <= n)``            ``present[A[i]] = ``true``;``    ``}` `    ``// Find the first element which didn't``    ``// appear in the original array``    ``for` `(``int` `i = 1; i <= n; i++)``        ``if` `(!present[i])``            ``return` `i;` `    ``// If the original array was of the``    ``// type {1, 2, 3} in its sorted form``    ``return` `n + 1;``}` `// Driver code``int` `main()``{` `    ``int` `A[] = { 0, 10, 2, -10, -20 };``    ``int` `size = ``sizeof``(A) / ``sizeof``(A);``    ``cout << firstMissingPos(A, size);``}` `// This code is contributed by gp6`

## Java

 `// Java Program to find the smallest``// positive missing number``import` `java.util.Arrays;``public` `class` `GFG {` `    ``static` `int` `solution(``int``[] A)``    ``{``        ``int` `n = A.length;` `        ``// To mark the occurrence of elements``        ``boolean``[] present = ``new` `boolean``[n + ``1``];` `        ``// Mark the occurrences``        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``// Only mark the required elements``            ``// All non-positive elements and``            ``// the elements greater n + 1 will never``            ``// be the answer``            ``// For example, the array will be {1, 2, 3}``            ``// in the worst case and the result``            ``// will be 4 which is n + 1``            ``if` `(A[i] > ``0` `&& A[i] <= n)``                ``present[A[i]] = ``true``;``        ``}` `        ``// Find the first element which didn't``        ``// appear in the original array``        ``for` `(``int` `i = ``1``; i <= n; i++)``            ``if` `(!present[i])``                ``return` `i;` `        ``// If the original array was of the``        ``// type {1, 2, 3} in its sorted form``        ``return` `n + ``1``;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{` `        ``int` `A[] = { ``0``, ``10``, ``2``, -``10``, -``20` `};``        ``System.out.println(solution(A));``    ``}``}``// This code is contributed by 29AjayKumar`

## Python3

 `# Python3 Program to find the smallest``# positive missing number`  `def` `solution(A):  ``# Our original array` `    ``m ``=` `max``(A)  ``# Storing maximum value``    ``if` `m < ``1``:` `        ``# In case all values in our array are negative``        ``return` `1``    ``if` `len``(A) ``=``=` `1``:` `        ``# If it contains only one element``        ``return` `2` `if` `A[``0``] ``=``=` `1` `else` `1``    ``l ``=` `[``0``] ``*` `m``    ``for` `i ``in` `range``(``len``(A)):``        ``if` `A[i] > ``0``:``            ``if` `l[A[i] ``-` `1``] !``=` `1``:` `                ``# Changing the value status at the index of our list``                ``l[A[i] ``-` `1``] ``=` `1``    ``for` `i ``in` `range``(``len``(l)):` `        ``# Encountering first 0, i.e, the element with least value``        ``if` `l[i] ``=``=` `0``:``            ``return` `i ``+` `1``            ``# In case all values are filled between 1 and m``    ``return` `i ``+` `2` `# Driver Code``A ``=` `[``0``, ``10``, ``2``, ``-``10``, ``-``20``]``print``(solution(A))`

## C#

 `// C# Program to find the smallest``// positive missing number``using` `System;``using` `System.Linq;` `class` `GFG {``    ``static` `int` `solution(``int``[] A)``    ``{``        ``// Our original array` `        ``int` `m = A.Max(); ``// Storing maximum value` `        ``// In case all values in our array are negative``        ``if` `(m < 1) {``            ``return` `1;``        ``}``        ``if` `(A.Length == 1) {` `            ``// If it contains only one element``            ``if` `(A == 1) {``                ``return` `2;``            ``}``            ``else` `{``                ``return` `1;``            ``}``        ``}``        ``int` `i = 0;``        ``int``[] l = ``new` `int``[m];``        ``for` `(i = 0; i < A.Length; i++) {``            ``if` `(A[i] > 0) {``                ``// Changing the value status at the index of``                ``// our list``                ``if` `(l[A[i] - 1] != 1) {``                    ``l[A[i] - 1] = 1;``                ``}``            ``}``        ``}` `        ``// Encountering first 0, i.e, the element with least``        ``// value``        ``for` `(i = 0; i < l.Length; i++) {``            ``if` `(l[i] == 0) {``                ``return` `i + 1;``            ``}``        ``}` `        ``// In case all values are filled between 1 and m``        ``return` `i + 2;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] A = { 0, 10, 2, -10, -20 };``        ``Console.WriteLine(solution(A));``    ``}``}` `// This code is contributed by PrinciRaj1992`

## PHP

 ` 0)``        ``{``            ``if` `(``\$l``[``\$A``[``\$i``] - 1] != 1)``            ``{``                ` `                ``//Changing the value status at the index of our list``                ``\$l``[``\$A``[``\$i``] - 1] = 1;``            ``}``        ``}``    ``}``    ``for` `(``\$i` `= 0;``\$i` `< sizeof(``\$l``); ``\$i``++)``    ``{``         ` `        ``//Encountering first 0, i.e, the element with least value``        ``if` `(``\$l``[``\$i``] == 0)``            ``return` `\$i``+1;``    ``}``            ``//In case all values are filled between 1 and m``    ``return` `\$i``+2;   ``}` `// Driver Code``\$A` `= ``array``(0, 10, 2, -10, -20);``echo` `solution(``\$A``);``return` `0;``?>`

## Javascript

 ``
Output
`1`

Another Approach:

• The smallest positive integer is 1. First we will check if 1 is present in the array or not. If it is not present then 1 is the answer.
• If present then, again traverse the array. The largest possible answer is N+1 where N is the size of array. This will happen when array have all the elements from 1 to N. When we are traversing the array, if we find any number less than 1 or greater than N, then we will change it to 1. This will not change anything as answer will always between 1 to N+1. Now our array has elements from 1 to N.
• Now, for every ith number, increase arr[ (arr[i]-1) ] by N. But this will increase the value more than N. So, we will access the array by arr[(arr[i]-1)%N]. What we have done is for each value we have increased value at that index by N.
• We will find now which index has value less than N+1. Then i+1 will be our answer.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function for finding the first missing positive number` `int` `firstMissingPositive(``int` `arr[], ``int` `n)``{``    ``int` `ptr = 0;` `    ``// Check if 1 is present in array or not``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(arr[i] == 1) {``            ``ptr = 1;``            ``break``;``        ``}``    ``}` `    ``// If 1 is not present``    ``if` `(ptr == 0)``        ``return` `1;` `    ``// Changing values to 1``    ``for` `(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= 0 || arr[i] > n)``            ``arr[i] = 1;` `    ``// Updating indices according to values``    ``for` `(``int` `i = 0; i < n; i++)``        ``arr[(arr[i] - 1) % n] += n;` `    ``// Finding which index has value less than n``    ``for` `(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= n)``            ``return` `i + 1;` `    ``// If array has values from 1 to n``    ``return` `n + 1;``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `ans = firstMissingPositive(arr, n);` `    ``cout << ans;` `    ``return` `0;``}`

## C

 `// C program for the above approach``#include ``#include ` `// Function for finding the first``// missing positive number``int` `firstMissingPositive(``int` `arr[], ``int` `n)``{``    ``int` `ptr = 0;` `    ``// Check if 1 is present in array or not``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``if` `(arr[i] == 1)``        ``{``            ``ptr = 1;``            ``break``;``        ``}``    ``}` `    ``// If 1 is not present``    ``if` `(ptr == 0)``        ``return` `1;` `    ``// Changing values to 1``    ``for``(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= 0 || arr[i] > n)``            ``arr[i] = 1;` `    ``// Updating indices according to values``    ``for``(``int` `i = 0; i < n; i++)``        ``arr[(arr[i] - 1) % n] += n;` `    ``// Finding which index has value less than n``    ``for``(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= n)``            ``return` `i + 1;` `    ``// If array has values from 1 to n``    ``return` `n + 1;``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `ans = firstMissingPositive(arr, n);``    ` `    ``printf``(``"%d"``, ans);``    ` `    ``return` `0;``}` `// This code is contributed by shailjapriya`

## Java

 `// Java program for the above approach``import` `java.util.Arrays;` `class` `GFG{` `// Function for finding the first``// missing positive number``static` `int` `firstMissingPositive(``int` `arr[], ``int` `n)``{``    ``int` `ptr = ``0``;` `    ``// Check if 1 is present in array or not``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``        ``if` `(arr[i] == ``1``)``        ``{``            ``ptr = ``1``;``            ``break``;``        ``}``    ``}` `    ``// If 1 is not present``    ``if` `(ptr == ``0``)``        ``return` `(``1``);` `    ``// Changing values to 1``    ``for``(``int` `i = ``0``; i < n; i++)``        ``if` `(arr[i] <= ``0` `|| arr[i] > n)``            ``arr[i] = ``1``;` `    ``// Updating indices according to values``    ``for``(``int` `i = ``0``; i < n; i++)``        ``arr[(arr[i] - ``1``) % n] += n;` `    ``// Finding which index has value less than n``    ``for``(``int` `i = ``0``; i < n; i++)``        ``if` `(arr[i] <= n)``            ``return` `(i + ``1``);` `    ``// If array has values from 1 to n``    ``return` `(n + ``1``);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = { ``2``, ``3``, -``7``, ``6``, ``8``, ``1``, -``10``, ``15` `};``    ``int` `n = arr.length;``    ``int` `ans = firstMissingPositive(arr, n);``    ` `    ``System.out.println(ans);``}``}` `// This code is contributed by shailjapriya`

## Python3

 `# Python3 program for the above approach` `# Function for finding the first missing``# positive number``def` `firstMissingPositive(arr, n):``    ` `    ``ptr ``=` `0``    ` `    ``# Check if 1 is present in array or not``    ``for` `i ``in` `range``(n):``        ``if` `arr[i] ``=``=` `1``:``            ``ptr ``=` `1``            ``break``        ` `    ``# If 1 is not present``    ``if` `ptr ``=``=` `0``:``        ``return``(``1``)``        ` `    ``# Changing values to 1``    ``for` `i ``in` `range``(n):``        ``if` `arr[i] <``=` `0` `or` `arr[i] > n:``            ``arr[i] ``=` `1``            ` `    ``# Updating indices according to values``    ``for` `i ``in` `range``(n):``        ``arr[(arr[i] ``-` `1``) ``%` `n] ``+``=` `n``        ` `    ``# Finding which index has value less than n``    ``for` `i ``in` `range``(n):``        ``if` `arr[i] <``=` `n:``            ``return``(i ``+` `1``)` `    ``# If array has values from 1 to n``    ``return``(n ``+` `1``)` `# Driver Code` `# Given array``A ``=` `[ ``2``, ``3``, ``-``7``, ``6``, ``8``, ``1``, ``-``10``, ``15` `]` `# Size of the array``N ``=` `len``(A)` `# Function call``print``(firstMissingPositive(A, N))` `# This code is contributed by shailjapriya`

## C#

 `// C# program for the above approach``using` `System;``using` `System.Linq;``  ` `class` `GFG{` `// Function for finding the first missing``// positive number    ``static` `int` `firstMissingPositive(``int``[] arr, ``int` `n)``{``    ``int` `ptr = 0;``    ` `    ``// Check if 1 is present in array or not``    ``for``(``int` `i = 0; i < n; i++)``    ``{``        ``if` `(arr[i] == 1)``        ``{``            ``ptr = 1;``            ``break``;``        ``}``    ``}``  ` `    ``// If 1 is not present``    ``if` `(ptr == 0)``        ``return` `1;``  ` `    ``// Changing values to 1``    ``for``(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= 0 || arr[i] > n)``            ``arr[i] = 1;``  ` `    ``// Updating indices according to values``    ``for``(``int` `i = 0; i < n; i++)``        ``arr[(arr[i] - 1) % n] += n;``  ` `    ``// Finding which index has value less than n``    ``for``(``int` `i = 0; i < n; i++)``        ``if` `(arr[i] <= n)``            ``return` `i + 1;``  ` `    ``// If array has values from 1 to n``    ``return` `n + 1;``}` `// Driver code``public` `static` `void` `Main()``{``    ``int``[] A = { 2, 3, -7, 6, 8, 1, -10, 15 };``    ``int` `n = A.Length;``    ``int` `ans = firstMissingPositive(A, n);``    ` `    ``Console.WriteLine(ans);``}``}` `// This code is contributed by shailjapriya`

## Javascript

 ``

Output:

`4`

Time Complexity : O(n)
Space Complexity : O(1)

Another Approach:

1. Traverse the array, Ignore the elements which are greater than n and less than 1.
2. While traversing check a[i]!=a[a[i]-1] if this condition hold true or not .
3. If the above condition is true then swap a[i], a[a[i] – 1]  && swap until a[i] != a[a[i] – 1]  condition will fail .
4. Traverse the array and check whether a[i] != i + 1 then return i + 1.
5. If all are equal to its index then return n+1.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function for finding the first``// missing positive number``int` `firstMissingPositive(``int` `arr[], ``int` `n)``{``    ` `    ``// Loop to traverse the whole array``    ``for` `(``int` `i = 0; i < n; i++) {``      ` `        ``// Loop to check boundary``        ``// condition and for swapping``        ``while` `(arr[i] >= 1 && arr[i] <= n``               ``&& arr[i] != arr[arr[i] - 1]) {``            ``swap(arr[i], arr[arr[i] - 1]);``        ``}``    ``}``  ` `    ``// Checking any element which``    ``// is not equal to i+1``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(arr[i] != i + 1) {``            ``return` `i + 1;``        ``}``    ``}``  ` `    ``// Nothing is present return last index``    ``return` `n + 1;``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `ans = firstMissingPositive(arr, n);` `    ``cout << ans;` `    ``return` `0;``}``// This code is contributed by Harsh kedia`

## Java

 `// Java program for the above approach``import` `java.util.Arrays;` `class` `GFG{` `// Function for finding the first``// missing positive number``static` `int` `firstMissingPositive(``int` `arr[], ``int` `n)``{` `    ``// Check if 1 is present in array or not``    ``for``(``int` `i = ``0``; i < n; i++)``    ``{``      ` `      ``// Loop to check boundary``      ``// condition and for swapping``      ``while` `(arr[i] >= ``1` `&& arr[i] <= n``             ``&& arr[i] != arr[arr[i] - ``1``]) {``        ` `        ``int` `temp=arr[arr[i]-``1``];``            ``arr[arr[i]-``1``]=arr[i];``            ``arr[i]=temp;``      ``}``    ``}` `    ``// Finding which index has value less than n``    ``for``(``int` `i = ``0``; i < n; i++)``        ``if` `(arr[i] != i + ``1``)``            ``return` `(i + ``1``);` `    ``// If array has values from 1 to n``    ``return` `(n + ``1``);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ``int` `arr[] = {``2``, ``3``, -``7``, ``6``, ``8``, ``1``, -``10``, ``15` `};``    ``int` `n = arr.length;``    ``int` `ans = firstMissingPositive(arr, n);``    ` `    ``System.out.println(ans);``}``}` `// This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach``using` `System;``public` `class` `GFG{` `  ``// Function for finding the first``  ``// missing positive number``  ``static` `int` `firstMissingPositive(``int``[] arr, ``int` `n)``  ``{` `    ``// Check if 1 is present in array or not``    ``for``(``int` `i = 0; i < n; i++)``    ``{` `      ``// Loop to check boundary``      ``// condition and for swapping``      ``while` `(arr[i] >= 1 && arr[i] <= n``             ``&& arr[i] != arr[arr[i] - 1]) {` `        ``int` `temp = arr[arr[i] - 1];``        ``arr[arr[i] - 1] = arr[i];``        ``arr[i] = temp;``      ``}``    ``}` `    ``// Finding which index has value less than n``    ``for``(``int` `i = 0; i < n; i++)``      ``if` `(arr[i] != i + 1)``        ``return` `(i + 1);` `    ``// If array has values from 1 to n``    ``return` `(n + 1);``  ``}` `  ``// Driver Code` `  ``static` `public` `void` `Main ()``  ``{` `    ``int``[] arr = {2, 3, -7, 6, 8, 1, -10, 15 };``    ``int` `n = arr.Length;``    ``int` `ans = firstMissingPositive(arr, n);` `    ``Console.WriteLine(ans);``  ``}``}` `// This code is contributed by ab2127`

## Javascript

 ``

Output:

`4`

Time Complexity: O(n)

Space Complexity: O(1)

https://youtu.be/_OAFHDVihjo
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes

My Personal Notes arrow_drop_up