Find the smallest positive number missing from an unsorted array | Set 3
Last Updated :
02 May, 2022
Given an unsorted array with both positive and negative elements. The task is to find the smallest positive number missing from the array.
Examples:
Input: arr[] = {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1
Input: arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 }
Output: 4
Input: arr[] = {1, 1, 0, -1, -2}
Output: 2
Approach :
We have already discussed some of the techniques to find the smallest positive number missing from an unsorted array.
Find the smallest positive number missing from an unsorted array | Set 1
Find the smallest positive number missing from an unsorted array | Set 2
Here, we use set to store all positive integers and find the first missing positive integer.
C++
#include <bits/stdc++.h>
using namespace std;
int findMissingPositive( int arr[], int n)
{
int m = 1;
set< int > x;
for ( int i = 0; i < n; i++) {
if (m < arr[i]) {
x.insert(arr[i]);
}
else if (m == arr[i]) {
m = m + 1;
while (x.count(m)) {
x.erase(m);
m = m + 1;
}
}
}
return m;
}
int main()
{
int arr[] = { 2, 3, -7, 6, 8, 1, -10, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << findMissingPositive(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int findMissingPositive( int arr[], int n)
{
int m = 1 ;
HashSet<Integer> x = new HashSet<Integer>();
for ( int i = 0 ; i < n; i++)
{
if (m < arr[i])
{
x.add(arr[i]);
}
else if (m == arr[i])
{
m = m + 1 ;
while (x.contains(m))
{
x.remove(m);
m = m + 1 ;
}
}
}
return m;
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , - 7 , 6 , 8 , 1 , - 10 , 15 };
int n = arr.length;
System.out.println(findMissingPositive(arr, n));
}
}
|
Python3
def findMissingPositive(arr, n):
m = 1
x = []
for i in range (n):
if (m < arr[i]):
x.append(arr[i])
elif (m = = arr[i]):
m = m + 1
while (x.count(m)):
x.remove(m)
m = m + 1
return m
if __name__ = = '__main__' :
arr = [ 2 , 3 , - 7 , 6 , 8 , 1 , - 10 , 15 ]
n = len (arr)
print (findMissingPositive(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int findMissingPositive( int []arr, int n)
{
int m = 1;
HashSet< int > x = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
if (m < arr[i])
{
x.Add(arr[i]);
}
else if (m == arr[i])
{
m = m + 1;
while (x.Contains(m))
{
x.Remove(m);
m = m + 1;
}
}
}
return m;
}
public static void Main(String[] args)
{
int []arr = { 2, 3, -7, 6, 8, 1, -10, 15 };
int n = arr.Length;
Console.WriteLine(findMissingPositive(arr, n));
}
}
|
Javascript
<script>
function findMissingPositive(arr, n)
{
let m = 1;
let x = new Set();
for (let i = 0; i < n; i++) {
if (m < arr[i]) {
x.add(arr[i]);
}
else if (m == arr[i]) {
m = m + 1;
while (x.has(m)) {
x. delete (m);
m = m + 1;
}
}
}
return m;
}
let arr = [2, 3, -7, 6, 8, 1, -10, 15];
let n = arr.length;
document.write(findMissingPositive(arr, n));
</script>
|
Time Complexity: O(nlog(n))
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...