Find the smallest positive number missing from an unsorted array | Set 2 - GeeksforGeeks

22 Apr, 2021
Given an unsorted array with both positive and negative elements. Find the smallest positive number missing from the array in O(n) time using constant extra space. It is allowed to 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 
 
We have discussed an O(n) time and O(1) extra space solution in the previous post. In this post, another alternative solution is discussed. We make the value at the index corresponding to the given array element equal to an array element. For example: consider the array = {2, 3, 7, 6, 8, -1, -10, 15}. To mark the presence of element 2 in this array, we make arr[2-1] = 2. In array subscript [2-1], 2 is the element to be marked and 1 is subtracted because we are mapping an element value range [1, N] on index value range [0, N-1]. But if we make arr[1] = 2, we will lose data stored at arr[1]. To avoid this, we first store the value present at arr[1] and then update it. Next, we will mark the presence of element previously present at arr[1], i.e. 3. Clearly this lead to some type of random traversal over the array. Now we have to specify a condition to mark the end of this traversal. There are three conditions that mark the end of this traversal: 1. If the element to be marked is negative: No need to mark the presence of this element as we are interested in finding the first missing positive integer. So if a negative element is found, simply end the traversal as no more marking of the presence of an element is done. 2. If the element to be marked is greater than N: No need to mark the presence of this element because if this element is present then certainly it has taken a place of an element in the range [1, N] in an array of size N and hence ensuring that our answer lies in the range[1, N]. So simply end the traversal as no more marking of the presence of an element is done. 3. If the presence of the current element is already marked: Suppose the element to be marked present is val. If arr[val-1] = val, then we have already marked the presence of this element. So simply end the traversal as no more marking of the presence of an element is done. Also note that it is possible that all the elements of an array in the range [1, N] are not marked present in the current traversal. To ensure that all the elements in the range are marked present, we check each element of the array lying in this range. If the element is not marked, then we start a new traversal beginning from that array element.After we have marked the presence of all array elements lying in the range [1, N], we check which index value ind is not equal to ind+1. If arr[ind] is not equal to ind+1, then ind+1 is the smallest positive missing number. Recall that we are mapping index value range [0, N-1] to element value range [1, N], so 1 is added to ind. If no such ind is found, then all elements in the range [1, N] are present in the array. So the first missing positive number is N+1.How does this solution work in O(n) time? Observe that each element in the range [1, N] is traversed at most twice in the worst case. First while performing a traversal started from some other element in the range. Second when checking if a new traversal is required to be initiated from this element to mark the presence of unmarked elements. In the worst case, each element in the range [1, N] is present in the array and thus all N elements are traversed twice. So total computations are 2*n, and hence the time complexity is O(n).Below is the implementation of above approach:  
C++
Java
Python 3
C#
PHP
Javascript
/* CPP program to find the smallest  positive missing number */#include <bits/stdc++.h>using namespace std; // Function to find smallest positive// missing number.int findMissingNo(int arr[], int n){    // to store current array element    int val;     // to store next array element in    // current traversal    int nextval;     for (int i = 0; i < n; i++) {         // if value is negative or greater        // than array size, then it cannot        // be marked in array. So move to        // next element.        if (arr[i] <= 0 || arr[i] > n)            continue;         val = arr[i];         // traverse the array until we        // reach at an element which        // is already marked or which        // could not be marked.        while (arr[val - 1] != val) {            nextval = arr[val - 1];            arr[val - 1] = val;            val = nextval;            if (val <= 0 || val > n)                break;        }    }     // find first array index which is    // not marked which is also the    // smallest positive missing    // number.    for (int i = 0; i < n; i++) {        if (arr[i] != i + 1) {            return i + 1;        }    }     // if all indices are marked, then    // smallest missing positive    // number is array_size + 1.    return n + 1;} // Driver codeint main(){    int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 };    int arr_size = sizeof(arr) / sizeof(arr[0]);    int missing = findMissingNo(arr, arr_size);    cout << "The smallest positive missing number is "         << missing;    return 0;}
/* Java program to find the smallestpositive missing number */import java.io.*; class GFG {     // Function to find smallest positive    // missing number.    static int findMissingNo(int []arr, int n)    {        // to store current array element        int val;             // to store next array element in        // current traversal        int nextval;             for (int i = 0; i < n; i++) {                 // if value is negative or greater            // than array size, then it cannot            // be marked in array. So move to            // next element.            if (arr[i] <= 0 || arr[i] > n)                continue;                 val = arr[i];                 // traverse the array until we            // reach at an element which            // is already marked or which            // could not be marked.            while (arr[val - 1] != val) {                nextval = arr[val - 1];                arr[val - 1] = val;                val = nextval;                if (val <= 0 || val > n)                    break;            }        }             // find first array index which is        // not marked which is also the        // smallest positive missing        // number.        for (int i = 0; i < n; i++) {            if (arr[i] != i + 1) {                return i + 1;            }        }             // if all indices are marked, then        // smallest missing positive        // number is array_size + 1.        return n + 1;    }         // Driver code    public static void main (String[] args)    {        int arr[] = { 2, 3, 7, 6, 8, -1, -10, 15 };        int arr_size = arr.length;                 int missing = findMissingNo(arr, arr_size);                 System.out.println( "The smallest positive"                + " missing number is " + missing);    }} // This code is contributed by anuj_67.
# Python 3 program to find the smallest# positive missing number # Function to find smallest positive# missing number.def findMissingNo(arr, n):     # to store current array element     # to store next array element in    # current traversal    for i in range(n) :         # if value is negative or greater        # than array size, then it cannot        # be marked in array. So move to        # next element.        if (arr[i] <= 0 or arr[i] > n):            continue         val = arr[i]         # traverse the array until we        # reach at an element which        # is already marked or which        # could not be marked.        while (arr[val - 1] != val):            nextval = arr[val - 1]            arr[val - 1] = val            val = nextval            if (val <= 0 or val > n):                break     # find first array index which is    # not marked which is also the    # smallest positive missing    # number.    for i in range(n):        if (arr[i] != i + 1) :            return i + 1     # if all indices are marked, then    # smallest missing positive    # number is array_size + 1.    return n + 1 # Driver codeif __name__ == "__main__":    arr = [ 2, 3, 7, 6, 8, -1, -10, 15 ]    arr_size = len(arr)    missing = findMissingNo(arr, arr_size)    print( "The smallest positive",           "missing number is ", missing) # This code is contributed# by ChitraNayal
/* C# program to find the smallestpositive missing number */using System; class GFG{    // Function to find smallest    // positive missing number.    static int findMissingNo(int []arr,                             int n)    {        // to store current        // array element        int val;             // to store next array element        // in current traversal        int nextval;             for (int i = 0; i < n; i++)        {                 // if value is negative or greater            // than array size, then it cannot            // be marked in array. So move to            // next element.            if (arr[i] <= 0 || arr[i] > n)                continue;                 val = arr[i];                 // traverse the array until we            // reach at an element which            // is already marked or which            // could not be marked.            while (arr[val - 1] != val)            {                nextval = arr[val - 1];                arr[val - 1] = val;                val = nextval;                if (val <= 0 || val > n)                    break;            }        }             // find first array index which        // is not marked which is also        // the smallest positive missing        // number.        for (int i = 0; i < n; i++)        {            if (arr[i] != i + 1)            {                return i + 1;            }        }             // if all indices are marked,        // then smallest missing        // positive number is        // array_size + 1.        return n + 1;    }         // Driver code    public static void Main (String[] args)    {        int []arr = {2, 3, 7, 6,                     8, -1, -10, 15};        int arr_size = arr.Length;                 int missing = findMissingNo(arr, arr_size);                 Console.Write("The smallest positive" +                        " missing number is " +                                      missing);    }} // This code is contributed// by shiv_bhakt.
<?php// PHP program to find// the smallest positive// missing number // Function to find smallest// positive missing number.function findMissingNo($arr, $n){    // to store current    // array element    $val;     // to store next array element    // in current traversal    $nextval;     for ($i = 0; $i < $n; $i++)    {         // if value is negative or        // greater than array size,        // then it cannot be marked        // in array. So move to        // next element.        if ($arr[$i] <= 0 ||            $arr[$i] > $n)            continue;         $val = $arr[$i];         // traverse the array until        // we reach at an element        // which is already marked        // or which could not be marked.        while ($arr[$val - 1] != $val)        {            $nextval = $arr[$val - 1];            $arr[$val - 1] = $val;            $val = $nextval;            if ($val <= 0 ||                $val > $n)                break;        }    }     // find first array index    // which is not marked    // which is also the smallest    // positive missing number.    for ($i = 0; $i < $n; $i++)    {        if ($arr[$i] != $i + 1)        {            return $i + 1;        }    }     // if all indices are marked,    // then smallest missing    // positive number is    // array_size + 1.    return $n + 1;} // Driver code$arr = array(2, 3, 7, 6, 8,            -1, -10, 15);$arr_size = sizeof($arr) /            sizeof($arr[0]);$missing = findMissingNo($arr,                         $arr_size);echo "The smallest positive " .         "missing number is " ,                      $missing; // This code is contributed// by shiv_bhakt.?>
<script> /* Javascript program to find the smallest  positive missing number */ // Function to find smallest positive// missing number.function findMissingNo(arr, n){    // to store current array element    var val;     // to store next array element in    // current traversal    var nextval;     for (var i = 0; i < n; i++) {         // if value is negative or greater        // than array size, then it cannot        // be marked in array. So move to        // next element.        if (arr[i] <= 0 || arr[i] > n)            continue;         val = arr[i];         // traverse the array until we        // reach at an element which        // is already marked or which        // could not be marked.        while (arr[val - 1] != val) {            nextval = arr[val - 1];            arr[val - 1] = val;            val = nextval;            if (val <= 0 || val > n)                break;        }    }     // find first array index which is    // not marked which is also the    // smallest positive missing    // number.    for (var i = 0; i < n; i++) {        if (arr[i] != i + 1) {            return i + 1;        }    }     // if all indices are marked, then    // smallest missing positive    // number is array_size + 1.    return n + 1;} // Driver codevar arr = [ 2, 3, 7, 6, 8, -1, -10, 15 ];var arr_size = arr.length;var missing = findMissingNo(arr, arr_size);document.write(  "The smallest positive missing number is "     + missing);  </script>
The smallest positive missing number is 1
 
Time Complexity: O(n) Auxiliary Space: O(1) 
vt_m
Vishal_Khoda
ukasp
noob2000
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number