Find the smallest positive number missing from an unsorted array | Set 1

Given an unsorted array arr[] with both positive and negative elements, the task is to find the smallest positive number missing from the array.
Note: You can modify the original array.
Examples:
Input: Â arr[] = {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1Input: Â arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }
Output: 4Input: arr[] = {1, 1, 0, -1, -2}
Output: 2
Naive Approach:
A naive method to solve this problem is to search all positive integers, starting from 1 in the given array.Â
Time Complexity: O(N2) because we may have to search at most n+1 numbers in the given array.
Auxiliary Space: O(1)
Smallest positive number missing from an unsorted array by Marking Elements:
The idea is to mark the elements which are present in the array then traverse over the marked array and return the first element which is not marked.
Follow the steps below to solve the problem:
- Create a list full of 0’s with the size of the max value of the given array.Â
- Now, whenever we encounter any positive value in the original array, change the index value of the list to 1.Â
- After that simply iterate through the modified list, the first 0 encountered, (index value + 1) should be the answer.
Below is the implementation of the above approach.
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to return the first missing positive number from// the given unsorted arrayint 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 codeint main(){Â
    int arr[] = { 0, 10, 2, -10, -20 };    int size = sizeof(arr) / sizeof(arr[0]);    cout << firstMissingPos(arr, size);}Â
// This code is contributed by Aditya Kumar (adityakumar129) |
C
// C implementation of the approach#include <stdbool.h>#include <stdio.h>Â
// Function to return the first missing positive number from// the given unsorted arrayint firstMissingPos(int A[], int n){Â
    // To mark the occurrence of elements    bool present[n + 1];    for (int i = 0; i < n; i++)        present[i] = 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 codeint main(){Â
    int arr[] = { 0, 10, 2, -10, -20 };    int size = sizeof(arr) / sizeof(arr[0]);    printf("%d", firstMissingPos(arr, size));}Â
// This code is contributed by Aditya Kumar (adityakumar129) |
Java
// Java Program to find the smallest positive missing numberimport java.util.*;public class GFG {Â
    static int solution(int[] A)    {        int n = A.length;        // Let this 1e6 be the maximum element provided in        // the array;        int N = 1000010;Â
        // To mark the occurrence of elements        boolean[] present = new boolean[N];Â
        int maxele = Integer.MIN_VALUE;Â
        // 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 maximum element so that if all the            // elements are in order can directly return the            // next number            maxele = Math.max(maxele, A[i]);        }Â
        // 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 maxele + 1;    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = { 0, 10, 2, -10, -20 };        System.out.println(solution(arr));    }}Â
// This code is contributed by Aditya Kumar (adityakumar129) |
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 Codeif __name__ == '__main__':Â Â Â Â arr = [0, 10, 2, -10, -20]Â Â Â Â print(solution(arr)) |
C#
// C# Program to find the smallest// positive missing numberusing 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[0] == 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[] arr = { 0, 10, 2, -10, -20 };        Console.WriteLine(solution(arr));    }}Â
// This code is contributed by PrinciRaj1992 |
PHP
<?php // PHP Program to find the smallest// positive missing number  function 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 (sizeof($A) == 1)    {         //If it contains only one element        if ($A[0] == 1)            return 2 ;        else            return 1 ;    }           $l = array_fill(0, $m, NULL);    for($i = 0; $i < sizeof($A); $i++)    {               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 = 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$arr = array(0, 10, 2, -10, -20);echo solution($arr);return 0;?> |
Javascript
<script>// Javascript Program to find the smallest// positive missing numberÂ
    function solution(A)    {        let n = A.length;        // To mark the occurrence of elements        let present = new Array(n+1);                          for(let i=0;i<n+1;i++)        {            present[i]=false;        }        // Mark the occurrences        for (let 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 (let 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    let arr = [0, 10, 2, -10, -20]    document.write(solution(arr));     </script> |
1
Time Complexity: O(N), Only two traversals are needed.
Auxiliary Space: O(N), using the list will require extra space
Smallest positive number missing from an unsorted Array by using array elements as Index:
The idea is to use array elements as an index. To mark the presence of an element x, 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 segregate positive from negative numbers as the first step and then apply the approach.
Follow the steps below to solve the problem:
- Segregate positive numbers from others i.e., move all non-positive numbers to the left side.
- Now ignore non-positive elements and consider only the part of the array which contains all positive elements.Â
- Traverse the array containing all positive numbers and to mark the presence of an element x, change the sign of value at index x to negative.Â
- Traverse the array again and print the first index which has a positive value.Â
Below is the implementation of the above approach.
v
1
Time Complexity: O(N), Traversing the array of size N.
Auxiliary Space: O(1)
Smallest positive number missing from an unsorted array by changing the input Array
The idea is to mark the elements in the array which are greater than N and less than 1 with 1.
Follow the steps below to solve the problem:
- 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 the array.Â
- When traversing the array, if we find any number less than 1 or greater than N, change it to 1.Â
- This will not change anything as the answer will always be 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].
- We will find now which index has a 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 <bits/stdc++.h>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 codeint main(){Â Â Â Â int arr[] = { 0, 10, 2, -10, -20 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    int ans = firstMissingPositive(arr, n);Â
    cout << ans;Â
    return 0;} |
C
// C program for the above approach#include <stdio.h>#include <stdlib.h>Â
// Function for finding the first// missing positive numberint 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 codeint main(){Â Â Â Â int arr[] = { 0, 10, 2, -10, -20 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â Â Â Â int ans = firstMissingPositive(arr, n);Â
    printf("%d", ans);Â
    return 0;}Â
// This code is contributed by shailjapriya |
Java
// Java program for the above approachimport 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[] = { 0, 10, 2, -10, -20 };        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 numberdef 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 Codeif __name__ == '__main__':    # Given array    A = [0, 10, 2, -10, -20]         # 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 approachusing 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 = { 0, 10, 2, -10, -20 };        int n = A.Length;        int ans = firstMissingPositive(A, n);Â
        Console.WriteLine(ans);    }}Â
// This code is contributed by shailjapriya |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function for finding the first // missing positive numberfunction firstMissingPositive(arr, n){    let ptr = 0;         // Check if 1 is present in array or not    for(let 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(let i = 0; i < n; i++)        if (arr[i] <= 0 || arr[i] > n)            arr[i] = 1;Â
    // Updating indices according to values    for(let i = 0; i < n; i++)        arr[(arr[i] - 1) % n] += n;Â
    // Finding which index has value less than n    for(let 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 let arr = [ 0, 10, 2, -10, -20 ];let n = arr.length;let ans = firstMissingPositive(arr, n);Â
document.write(ans);Â
// This code is contributed by telimayurÂ
</script> |
1
Time Complexity: O(N), Traversing over the array
Auxiliary Space: Â O(1)Â
Smallest positive number missing from an unsorted array by Swapping:
The idea is to swap the elements which are in the range 1 to N should be placed at their respective indexes.
Follow the steps below to solve the problem:
- Traverse the array, Ignore the elements which are greater than N and less than 1.
- While traversing, check if a[i] ≠a[a[i]-1] holds true or not .
- If the above condition is true then swap a[i] and a[a[i] – 1]  and swap until (a[i] ≠a[a[i] – 1]) condition fails.
- Traverse the array and check whether a[i] ≠i + 1 then return i + 1.
- 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 <bits/stdc++.h>using namespace std;Â
// Function for finding the first// missing positive numberint 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 codeint main(){Â Â Â Â int arr[] = { 0, 10, 2, -10, -20 };Â Â Â Â int n = sizeof(arr) / sizeof(arr[0]);Â
    int ans = firstMissingPositive(arr, n);Â
    cout << ans;Â
    return 0;}// This code is contributed by Harsh kedia |
Java
// Java program for the above approachimport 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[] = { 0, 10, 2, -10, -20 };        int n = arr.length;        int ans = firstMissingPositive(arr, n);Â
        System.out.println(ans);    }}Â
// This code is contributed by mohit kumar 29. |
Python3
# Python program for the above approachÂ
Â
# Function for finding the first# missing positive numberdef firstMissingPositive(arr, n):Â
    # Loop to traverse the whole array    for i in range(n):Â
        # Loop to check boundary        # condition and for swapping        while (arr[i] >= 1 and arr[i] <= n               and arr[i] != arr[arr[i] - 1]):            temp = arr[i]            arr[i] = arr[arr[i] - 1]            arr[temp - 1] = tempÂ
    # Checking any element which    # is not equal to i + 1    for i in range(n):        if (arr[i] != i + 1):            return i + 1Â
    # Nothing is present return last index    return n + 1Â
Â
# Driver codeif __name__ == '__main__':Â Â Â Â arr = [0, 10, 2, -10, -20]Â Â Â Â n = len(arr)Â Â Â Â ans = firstMissingPositive(arr, n)Â Â Â Â print(ans)Â
# This code is contributed by shivanisinghss2110 |
C#
// C# program for the above approachusing 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 = { 0, 10, 2, -10, -20 };        int n = arr.Length;        int ans = firstMissingPositive(arr, n);Â
        Console.WriteLine(ans);    }}Â
// This code is contributed by ab2127 |
Javascript
<script>// Javascript program for the above approachÂ
// Function for finding the first// missing positive numberfunction firstMissingPositive(arr, n){    // Check if 1 is present in array or not    for(let 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]) {                  let temp=arr[arr[i]-1];            arr[arr[i]-1]=arr[i];            arr[i]=temp;      }    }      // Finding which index has value less than n    for(let 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 Codelet arr=[ 0, 10, 2, -10, -20 ];let n = arr.length;let ans = firstMissingPositive(arr, n);document.write(ans);                                 Â
Â
// This code is contributed by patel2127</script> |
1
Time Complexity: O(N), Only two traversals are needed.
Auxiliary Space: O(1), No extra space is needed
Smallest positive number missing from an unsorted array using Sorting:
The idea is to sort the array and then check for the smallest missing number (start from 1) if it is present then increment it.
Follow the steps below to solve the problem:
- First sort the array and the smallest positive integer is 1.
- So, take ans=1 and iterate over the array once and check whether arr[i] = ans (Checking for value from 1 up to the missing number).
- By iterating if that condition meets where arr[i] = ans then increment ans by 1 and again check for the same condition until the size of the array.
- After one scan of the array, the missing number is stored in ans variable.
- Now return that ans to the function.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std;Â
// Function to find first positive missing numberint firstMissingPositive(vector<int>& nums){Â Â Â Â sort(nums.begin(), nums.end());Â Â Â Â int ans = 1;Â Â Â Â for (int i = 0; i < nums.size(); i++) {Â Â Â Â Â Â Â Â if (nums[i] == ans) {Â Â Â Â Â Â Â Â Â Â Â Â ans++;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return ans;}Â
// Driver codeint main(){    vector<int> arr = { 0, 10, 2, -10, -20 };    // Function call    cout << firstMissingPositive(arr);    return 0;} |
Java
/*package whatever // do not write package name here */import java.io.*;import java.util.Arrays;class GFG {    public static int firstMissingPositive(int[] nums,                                           int n)    {        Arrays.sort(nums);        int ans = 1;        for (int i = 0; i < n; i++) {            if (nums[i] == ans)                ans++;        }        return ans;    }    public static void main(String[] args)    {        int arr[] = { 0, 10, 2, -10, -20 };        int n = arr.length;        int ans = firstMissingPositive(arr, n);        System.out.println(ans);    }} |
Python3
# Python code for the same approachfrom functools import cmp_to_keyÂ
Â
def cmp(a, b):Â Â Â Â return (a - b)Â
Â
def firstMissingPositive(nums):Â
    nums.sort(key = cmp_to_key(cmp))    ans = 1    for i in range(len(nums)):Â
        if(nums[i] == ans):            ans += 1Â
    return ansÂ
Â
# driver codeif __name__ == '__main__':Â Â Â Â arr = [0, 10, 2, -10, -20]Â Â Â Â print(firstMissingPositive(arr))Â
# This code is contributed by shinjanpatra |
C#
// C# program for the above approachusing System;Â
public class GFG {    static public int firstMissingPositive(int[] nums,                                           int n)    {        Array.Sort(nums);        int ans = 1;        for (int i = 0; i < n; i++) {            if (nums[i] == ans)                ans++;        }        return ans;    }Â
    // Driver Code    static public void Main()    {Â
        int[] arr = { 0, 10, 2, -10, -20 };        int n = arr.Length;        int ans = firstMissingPositive(arr, n);Â
        Console.WriteLine(ans);    }}Â
// This code is contributed by kothavvsaakash |
Javascript
<script>Â
function firstMissingPositive(nums){Â Â Â Â nums.sort((a, b)=>a-b);Â Â Â Â let ans = 1;Â Â Â Â for(let i = 0; i < nums.length; i++)Â Â Â Â {Â Â Â Â Â Â Â Â if(nums[i] == ans)Â Â Â Â Â Â Â Â Â Â Â Â ans++;Â Â Â Â }Â Â Â Â return ans;}Â
// driver codelet arr = [0, 10, 2, -10, -20];document.write(firstMissingPositive(arr));Â
// This code is contributed by shinjanpatraÂ
</script> |
1
Time Complexity: O(N*log(N)), Time required to sort the array
Auxiliary Space: O(1)Â
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



