Given an array arr[] containing integers. The task is to find the largest positive integer x missing from the array such that min(arr[]) < x < max(arr[]).
Examples
Input: arr[] = {2, 3, 7, 6, 8}
Output: 5
Explanation: 5 is the largest positive integer missing from arr[] and 2 < 5 < 8.
Input: arr[] = { 2, 3, -7, 1, 4 }
Output: -1
Naive Approach: Sort the array in descending and return the first missing positive number. If none is missing, return -1.
Algorithm:
- Initialize variables max_val and min_val to store the maximum and minimum values in the given array, and initialize an array of size (max_val – min_val + 1) with all elements as 0.
- Traverse the given array and for each element, if it lies within the range [min_val, max_val], mark the corresponding index in the new array as 1.
- Traverse the new array starting from index 1 and find the first index i such that the corresponding element is 0. Return i + min_val as the answer.
- If no such index is found, return -1 to indicate that no missing positive integer was found in the given range.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int largestMissingPositive( int arr[], int n) {
sort(arr, arr + n, greater< int >());
int max_num = arr[0];
int min_num = arr[n - 1];
int missing_num = -1;
for ( int i = max_num - 1; i >= min_num + 1; i--) {
bool found = false ;
for ( int j = 0; j < n; j++) {
if (arr[j] == i) {
found = true ;
break ;
}
}
if (!found) {
missing_num = i;
break ;
}
}
return missing_num;
}
int main() {
int arr[] = { 2, 3, 7, 6, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
int missing_num = largestMissingPositive(arr, n);
if (missing_num == -1) {
cout << -1 << endl;
}
else {
cout << missing_num << endl;
}
return 0;
}
|
Java
import java.util.Arrays;
public class Main {
static int largestMissingPositive( int [] arr, int n) {
Arrays.sort(arr);
int maxNum = arr[n - 1 ];
int minNum = arr[ 0 ];
int missingNum = - 1 ;
for ( int i = maxNum - 1 ; i >= minNum + 1 ; i--) {
boolean found = false ;
for ( int j = 0 ; j < n; j++) {
if (arr[j] == i) {
found = true ;
break ;
}
}
if (!found) {
missingNum = i;
break ;
}
}
return missingNum;
}
public static void main(String[] args) {
int [] arr = { 2 , 3 , 7 , 6 , 8 };
int n = arr.length;
int missingNum = largestMissingPositive(arr, n);
if (missingNum == - 1 ) {
System.out.println(- 1 );
} else {
System.out.println(missingNum);
}
}
}
|
C#
using System;
using System.Linq;
public class GFG {
public static int LargestMissingPositive( int [] arr,
int n)
{
Array.Sort(arr, (x, y) => y.CompareTo(x));
int max_num = arr[0];
int min_num = arr[n - 1];
int missing_num = -1;
for ( int i = max_num - 1; i >= min_num + 1; i--) {
bool found = false ;
for ( int j = 0; j < n; j++) {
if (arr[j] == i) {
found = true ;
break ;
}
}
if (!found) {
missing_num = i;
break ;
}
}
return missing_num;
}
public static void Main()
{
int [] arr = { 2, 3, 7, 6, 8 };
int n = arr.Length;
int missing_num = LargestMissingPositive(arr, n);
if (missing_num == -1) {
Console.WriteLine(-1);
}
else {
Console.WriteLine(missing_num);
}
}
}
|
Javascript
function largestMissingPositive(arr, n) {
arr.sort();
arr.reverse();
let max_num = arr[0];
let min_num = arr[n - 1];
let missing_num = -1;
for (let i = max_num - 1; i >= min_num + 1; i--) {
let found = false ;
for (let j = 0; j < n; j++) {
if (arr[j] == i) {
found = true ;
break ;
}
}
if (!found) {
missing_num = i;
break ;
}
}
return missing_num;
}
let arr = [ 2, 3, 7, 6, 8 ];
let n = arr.length;
let missing_num = largestMissingPositive(arr, n);
if (missing_num == -1) {
console.log(-1);
}
else {
console.log(missing_num);
}
|
Time Complexity: O(N logN)
Time Complexity: O(1)
Efficient Approach: This problem can be solved by using Hashing. Build a Hashmap of all positive elements in the given array. After building Hashmap, look in the HashMap from reverse, and return the first missing positive number. If none is missing, return -1.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int firstMissingPositive(vector< int >& nums)
{
int n = nums.size();
map< int , int > m;
for ( int i = 0; i < n; i++) {
if (m.find(nums[i]) == m.end()) {
m.insert({ nums[i], 1 });
}
}
int ans = 0;
for (ans = m.rbegin()->first; ans > 0; ans--) {
if (m.find(ans) == m.end())
break ;
}
return ans;
}
int main()
{
vector< int > arr = { 2, 3, 7, 6, 8 };
int missing = firstMissingPositive(arr) == 0
? -1
: firstMissingPositive(arr);
cout << missing;
return 0;
}
|
Java
import java.util.*;
class GFG
{
public static int firstMissingPositive( int [] nums)
{
int n = nums.length;
HashMap<Integer, Integer> m = new HashMap<>();
for ( int i = 0 ; i < n; i++) {
if (m.containsKey(nums[i]) == false ) {
m.put(nums[i], 1 );
}
}
int ans = 0 ;
for (Map.Entry<Integer, Integer> temp :
m.entrySet()) {
ans = Math.max(ans, temp.getKey());
}
for (; ans > 0 ; ans--) {
if (m.containsKey(ans) == false )
break ;
}
return ans;
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , 7 , 6 , 8 };
if (firstMissingPositive(arr) == 0 )
System.out.print(- 1 );
else
System.out.print(firstMissingPositive(arr));
}
}
|
Python3
def firstMissingPositive(nums):
n = len (nums)
m = {}
for i in range (n):
if (nums[i] not in m):
m[nums[i]] = 1
ans = 0
for itm in m.keys():
ans = max (ans, itm)
while (ans > = 0 ):
if (ans not in m):
break
ans - = 1
return ans
arr = [ 2 , 3 , 7 , 6 , 8 ]
missing = - 1 if firstMissingPositive(arr) = = 0 else firstMissingPositive(arr)
print (missing)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static int firstMissingPositive( int [] nums)
{
int n = nums.Length;
Dictionary< int , int > m = new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
if (m.ContainsKey(nums[i]) == false ) {
m.Add(nums[i], 1);
}
}
int ans = 0;
foreach (KeyValuePair< int , int > temp in
m) {
ans = Math.Max(ans, temp.Key);
}
for (; ans > 0; ans--) {
if (m.ContainsKey(ans) == false )
break ;
}
return ans;
}
public static void Main(String[] args)
{
int [] arr = { 2, 3, 7, 6, 8 };
if (firstMissingPositive(arr) == 0)
Console.Write(-1);
else
Console.Write(firstMissingPositive(arr));
}
}
|
Javascript
<script>
const firstMissingPositive = (nums) => {
let n = nums.length;
let m = {};
for (let i = 0; i < n; i++) {
if (!(nums[i] in m)) {
m[nums[i]] = 1;
}
}
let ans = 0;
for (let itm in m) ans = Math.max(ans, itm);
for (; ans > 0; ans--) {
if (!(ans in m))
break ;
}
return ans;
}
let arr = [2, 3, 7, 6, 8];
let missing = firstMissingPositive(arr) == 0
? -1
: firstMissingPositive(arr);
document.write(missing);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)