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

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 previous post. In this post another alternative solution is discussed.
We make the value at index corresponding to given array element equal to array element. For example: consider the array = {2, 3, 7, 6, 8, -1, -10, 15}. To mark presence of element 2 in this array, we make arr[2-1] = 2. In array subscript [2-1], 2 is 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 loss data stored at arr[1]. To avoid this, we first store value present at arr[1] and then update it. Next we will mark 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 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 presence of an element is done.
2. If 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 range [1, N] in 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 presence of an element is done.
3. If presence of current element is already marked: Suppose 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 presence of an element is done.
Also note that it is possible that all the elements of array in the range [1, N] are not marked present in 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 element is not marked, then we start a new traversal beginning from that array element.

After we have marked 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 this solution works in O(n) time?
Observe that each element in range [1, N] is traversed at most twice in 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 worst case each element in the range [1, N] are 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

/* 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 code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Java program to find the smallest 
positive 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.

chevron_right


Python 3

# 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 code
if __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#

filter_none

edit
close

play_arrow

link
brightness_4
code

/* C# program to find the smallest 
positive 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right


Output:

The smallest positive missing number is 1

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



My Personal Notes arrow_drop_up

A Programmer and A Machine learning Enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vt_m, Vishal_Khoda, Ita_c



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.