First Missing Positive

Moderate
0/80
Average time to solve is 18m
510 upvotes
Asked in companies
SalesforceProtiumQualcomm

Problem statement

You are given an array 'ARR' of integers of length N. Your task is to find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can have negative numbers as well.

For example, the input [3, 4, -1, 1] should give output 2 because it is the smallest positive number that is missing in the input array.

Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line of input contains a single integer T, representing the number of test cases or queries to be run. 
Then the T test cases follow.

The first line of each test case contains a positive integer N which represents the length of the array.

The second line of each test case contains N integers representing the elements of the array 'ARR'.
Output Format :
For each test case, print a single integer denoting the minimum positive integer that is missing from the given input array.

Th output of each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.
Constraint :
1 <= T <= 10
1 <= N <= 10^5
-10^5 <= ARR[i] <= 10^5

Time Limit: 1 sec
Sample Input 1 :
1
5
3 2 -6 1 0
Sample Output 1:
4
Explanation for Input 1:
The first positive number is 1 and it is present in the array similarly 2 and 3 are also present in the array. 4 is missing from the array. Thus, the minimum positive integer that is missing is 4.
Sample Input 2 :
1
5
0 1 2 3 4
Sample Output 2:
5
Hint

Think of searching all the elements in the array.

Approaches (4)
Searching
  1. Since we are given an integer ‘N’, there could be a maximum of ‘N’ positive integers in the array.
  2. The minimum positive number is 1, hence we can search from 1 to N in the array.
  3. Run a loop from 1 to N, and search for each element in the array.
  4. If the element is present in the array then search for the next element.
  5. If it is not present then, the element is the answer.
  6. Otherwise, if all the elements between 1 to N are present in the array then the minimum positive integer that is missing would be N+1. So the answer would be N+1.
Time Complexity

O(N*N), where N is the length of the array.

 

Since for every positive integer, we need to traverse the whole array in two nested for loops to find the missing positive integer. Therefore, the time complexity here becomes O(N^2).

Space Complexity

O(1), as we are not using any extra space.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
First Missing Positive
Full screen
Console