Find first k natural numbers missing in given array - GeeksforGeeks

25 Jun, 2021
Given an array of size n and a number k, we need to print first k natural numbers that are not there in the given array.Examples: 
Input : [2 3 4] 
         k = 3
Output : [1 5 6]

Input  : [-2 -3 4] 
          k = 2
Output : [1 2]
1) Sort the given array. 2) After sorting, we find the position of the first positive number in the array. 3) Now we traverse the array and keep printing elements in gaps between two consecutive array elements. 4) If gaps don’t cover k missing numbers, we print numbers greater than the largest array element.  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find missing k numbers// in an array.#include <bits/stdc++.h>using namespace std; // Prints first k natural numbers in// arr[0..n-1]void printKMissing(int arr[], int n, int k){    sort(arr, arr + n);     // Find first positive number    int i = 0;    while (i < n && arr[i] <= 0)        i++;     // Now find missing numbers    // between array elements    int count = 0, curr = 1;    while (count < k && i < n) {        if (arr[i] != curr) {            cout << curr << " ";            count++;        }        else            i++;         curr++;    }     // Find missing numbers after    // maximum.    while (count < k) {        cout << curr << " ";        curr++;        count++;    }} // Driver codeint main(){    int arr[] = { 2, 3, 4 };    int n = sizeof(arr) / sizeof(arr[0]);    int k = 3;    printKMissing(arr, n, k);    return 0;}
// Java program to find missing k numbers// in an array.import java.util.Arrays; class GFG {    // Prints first k natural numbers in    // arr[0..n-1]    static void printKMissing(int[] arr, int n, int k)    {        Arrays.sort(arr);         // Find first positive number        int i = 0;        while (i < n && arr[i] <= 0)            i++;         // Now find missing numbers        // between array elements        int count = 0, curr = 1;        while (count < k && i < n) {            if (arr[i] != curr) {                System.out.print(curr + " ");                count++;            }            else                i++;            curr++;        }         // Find missing numbers after        // maximum.        while (count < k) {            System.out.print(curr + " ");            curr++;            count++;        }    }     // Driver code    public static void main(String[] args)    {        int[] arr = { 2, 3, 4 };        int n = arr.length;        int k = 3;        printKMissing(arr, n, k);    }}/* This code is contributed by Mr. Somesh Awasthi */
# Python3 program to find missing# k numbers in an array. # Prints first k natural numbers# in arr[0..n-1]def printKMissing(arr, n, k) :         arr.sort()     # Find first positive number    i = 0    while (i < n and arr[i] <= 0) :        i = i + 1     # Now find missing numbers    # between array elements    count = 0    curr = 1    while (count < k and i < n) :        if (arr[i] != curr) :            print(str(curr) + " ", end = '')            count = count + 1        else:            i = i + 1                 curr = curr + 1             # Find missing numbers after    # maximum.    while (count < k) :        print(str(curr) + " ", end = '')        curr = curr + 1        count = count + 1         # Driver codearr = [ 2, 3, 4 ]n = len(arr)k = 3printKMissing(arr, n, k); # This code is contributed# by Yatin Gupta
// C# program to find missing// k numbers in an array.using System; class GFG {    // Prints first k natural numbers    // in arr[0..n-1]    static void printKMissing(int[] arr,                              int n,                              int k)    {        Array.Sort(arr);         // Find first positive number        int i = 0;        while (i < n && arr[i] <= 0)            i++;         // Now find missing numbers        // between array elements        int count = 0, curr = 1;        while (count < k && i < n) {            if (arr[i] != curr) {                Console.Write(curr + " ");                count++;            }            else                i++;            curr++;        }         // Find missing numbers        // after maximum.        while (count < k) {            Console.Write(curr + " ");            curr++;            count++;        }    }     // Driver code    public static void Main()    {        int[] arr = {2, 3, 4};        int n = arr.Length;        int k = 3;        printKMissing(arr, n, k);    }} // This code is contributed by Nitin Mittal
<?php// PHP program to find missing k numbers// in an array. // Prints first k natural numbers in// arr[0..n-1]function printKMissing($arr, $n, $k){    sort($arr); sort($arr , $n);     // Find first positive number    $i = 0;    while ($i < $n && $arr[$i] <= 0)        $i++;     // Now find missing numbers    // between array elements    $count = 0; $curr = 1;    while ($count < $k && $i < $n) {        if ($arr[$i] != $curr) {            echo $curr , " ";            $count++;        }        else            $i++;         $curr++;    }     // Find missing numbers after    // maximum.    while ($count < $k) {        echo $curr , " ";        $curr++;        $count++;    }}     // Driver code    $arr =array ( 2, 3, 4 );    $n = sizeof($arr);    $k = 3;    printKMissing($arr, $n, $k); // This code is contributed by Nitin Mittal.?>
<script> // JavaScript program to find missing k numbers// in an array. // Prints first k natural numbers in// arr[0..n-1]function printKMissing(arr, n, k) {    arr.sort((a, b) => a - b);     // Find first positive number    let i = 0;    while (i < n && arr[i] <= 0)        i++;     // Now find missing numbers    // between array elements    let count = 0, curr = 1;    while (count < k && i < n) {        if (arr[i] != curr) {            document.write(curr + " ");            count++;        }        else            i++;         curr++;    }     // Find missing numbers after    // maximum.    while (count < k) {        document.write(curr, " ");        curr++;        count++;    }} // Driver codelet arr = new Array(2, 3, 4);let n = arr.length;let k = 3;printKMissing(arr, n, k); // This code is contributed by gfgking </script>
1 5 6 
Time Complexity: O(n Log n)
Alternative Method:1)We can use hashmap to search in O(1) time.2)Use a dictionary to store values in the array. 3)We run a loop from 1 to n+k and check whether they are in hashmap.4)If they are not present print the number. 5)if all k elements are found break the loop.  
C++
Java
Python3
C#
Javascript
// C++ code for// the above approach#include <bits/stdc++.h>using namespace std; // Program to print first k// missing numbervoid printmissingk(int arr[],                   int n, int k){  // Creating a hashmap  map<int, int> d;   // Iterate over array  for (int i = 0; i < n; i++)    d[arr[i]] = arr[i];   int cnt = 1;  int fl = 0;   // Iterate to find missing  // element  for (int i = 0; i < (n + k); i++)  {    if (d.find(cnt) == d.end())    {      fl += 1;      cout << cnt << " ";      if (fl == k)        break;    }    cnt += 1;  }} // Driver Codeint main(){  int arr[] = {1, 4, 3};  int n = sizeof(arr) /          sizeof(arr[0]);  int k = 3;;  printmissingk(arr, n, k);} // This code is contributed by Chitranayal
// Java code for// the above approachimport java.io.*;import java.util.HashMap; class GFG{     // Program to print first k    // missing number    static void printmissingk(int arr[], int n, int k)    {        // Creating a hashmap        HashMap<Integer, Integer> d = new HashMap<>();         // Iterate over array        for (int i = 0; i < n; i++)            d.put(arr[i], arr[i]);         int cnt = 1;        int fl = 0;         // Iterate to find missing        // element        for (int i = 0; i < (n + k); i++) {            if (!d.containsKey(cnt)) {                fl += 1;                System.out.print(cnt + " ");                if (fl == k)                    break;            }            cnt += 1;        }    }     // Driver Code    public static void main(String[] args)    {        int arr[] = { 1, 4, 3 };        int n = arr.length;        int k = 3;        printmissingk(arr, n, k);    }} // This code is contributed by subhammahato348.
# Python3 code for above approach # Program to print first k# missing numberdef printmissingk(arr,n,k):       #creating a hashmap    d={}         # Iterate over array    for i in range(len(arr)):        d[arr[i]]=arr[i]             cnt=1    fl=0         # Iterate to find missing    # element    for i in range(n+k):        if cnt not in d:            fl+=1            print(cnt,end=" ")            if fl==k:                break        cnt+=1    print() # Driver Codearr=[1,4,3]n=len(arr)k=3printmissingk(arr,n,k) #This code is contributed by Thirumalai Srinivasan
// C# code for// the above approachusing System;using System.Collections.Generic; public class GFG{   // Program to print first k  // missing number  static void printmissingk(int[] arr, int n, int k)  {     // Creating a hashmap    Dictionary<int,int> d = new Dictionary<int,int>();     // Iterate over array    for (int i = 0; i < n; i++)    {      d.Add(arr[i], arr[i]);    }    int cnt = 1;    int fl = 0;     // Iterate to find missing    // element    for (int i = 0; i < (n + k); i++)    {      if (!d.ContainsKey(cnt))      {        fl += 1;        Console.Write(cnt + " ");        if (fl == k)          break;      }      cnt += 1;    }  }   // Driver Code  static public void Main (){    int[] arr = { 1, 4, 3 };    int n = arr.Length;    int k = 3;    printmissingk(arr, n, k);  }} // This code is contributed by avanitrachhadiya2155
<script>// Javascript code for// the above approach // Program to print first k    // missing numberfunction printmissingk(arr,n,k){    // Creating a hashmap        let d = new Map();          // Iterate over array        for (let i = 0; i < n; i++)            d.set(arr[i], arr[i]);          let cnt = 1;        let fl = 0;          // Iterate to find missing        // element        for (let i = 0; i < (n + k); i++) {            if (!d.has(cnt)) {                fl += 1;                document.write(cnt + " ");                if (fl == k)                    break;            }            cnt += 1;        }} // Driver Codelet arr=[1, 4, 3];let  n = arr.length;let k = 3;printmissingk(arr, n, k);  // This code is contributed by ab2127</script>
2 5 6 
Time complexity: O(n+k)
This article is contributed by Biswajit Mohapatra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
YatinGupta
Thirumalaisrinivasan
ukasp
subhammahato348
avanitrachhadiya2155
gfgking
ab2127
Arrays
Sorting
Arrays
Sorting
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