Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if an Array is a permutation of numbers from 1 to N
Next article icon

Find all duplicate and missing numbers in given permutation array of 1 to N

Last Updated : 31 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N consisting of the first N natural numbers, the task is to find all the repeating and missing numbers over the range [1, N] in the given array.

Examples:

Input: arr[] = {1, 1, 2, 3, 3, 5}
Output: 
Missing Numbers: [4, 6]
Duplicate Numbers: [1, 3]
Explanation:
As 4 and 6 are not in arr[] Therefore they are missing and 1 is repeating two times and 3 is repeating two times so they are duplicate numbers. 

Input: arr[] = {1, 2, 2, 2, 4, 5, 7}
Output:
Missing Numbers: [3, 6]
Duplicate Numbers: [2]

Approach: The given problem can be solved using the idea discussed in this article where only one element is repeating and the other is duplicate. Follow the steps below to solve the given problem:

  • Initialize an array, say missing[] that stores the missing elements.
  • Initialize a set, say duplicate that stores the duplicate elements.
  • Traverse the given array arr[] using the variable i and perform the following steps:
    • If the value of arr[i] != arr[arr[i] - 1] is true, then the current element is not equal to the place where it is supposed to be if all numbers were present from 1 to N. So swap arr[i] and arr[arr[i] - 1].
    • Otherwise, it means the same element is present at arr[arr[i] - 1].
  • Traverse the given array arr[] using the variable i and if the value of arr[i] is not the same as (i + 1) then the missing element is (i + 1) and the duplicate element is arr[i].
  • After completing the above steps, print the elements stored in missing[] and duplicate[] as the result.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to find the duplicate and // the missing elements over the range // [1, N] void findElements(int arr[], int N) {     int i = 0;      // Stores the missing and duplicate     // numbers in the array arr[]     vector<int> missing;     set<int> duplicate;      // Making an iterator for set     set<int>::iterator it;      // Traverse the given array arr[]     while (i != N) {         cout << i << " # " ;         // Check if the current element         // is not same as the element at         // index arr[i] - 1, then swap         if (arr[i] != arr[arr[i] - 1]) {             swap(arr[i], arr[arr[i] - 1]);         }          // Otherwise, increment the index         else {             i++;         }     }      // Traverse the array again     for (i = 0; i < N; i++) {          // If the element is not at its         // correct position         if (arr[i] != i + 1) {              // Stores the missing and the             // duplicate elements             missing.push_back(i + 1);             duplicate.insert(arr[i]);         }     }      // Print the Missing Number     cout << "Missing Numbers: ";     for (auto& it : missing)         cout << it << ' ';      // Print the Duplicate Number     cout << "\nDuplicate Numbers: ";     for (auto& it : duplicate)         cout << it << ' '; }  // Driver code int main() {     int arr[] = { 1, 2, 2, 2, 4, 5, 7 };     int N = sizeof(arr) / sizeof(arr[0]);     findElements(arr, N);      return 0; } 
Java
// Java program for the above approach import java.util.ArrayList; import java.util.HashSet;  class GFG {      // Function to find the duplicate and     // the missing elements over the range     // [1, N]     static void findElements(int arr[], int N) {         int i = 0;          // Stores the missing and duplicate         // numbers in the array arr[]         ArrayList<Integer> missing = new ArrayList<Integer>();         HashSet<Integer> duplicate = new HashSet<Integer>();          // Traverse the given array arr[]         while (i != N) {             // Check if the current element             // is not same as the element at             // index arr[i] - 1, then swap             if (arr[i] != arr[arr[i] - 1]) {                 int temp = arr[i];                 arr[i] = arr[arr[i] - 1];                 arr[temp - 1] = temp;             }              // Otherwise, increment the index             else {                 i++;             }         }          // Traverse the array again         for (i = 0; i < N; i++) {              // If the element is not at its             // correct position             if (arr[i] != i + 1) {                  // Stores the missing and the                 // duplicate elements                 missing.add(i + 1);                 duplicate.add(arr[i]);             }         }          // Print the Missing Number         System.out.print("Missing Numbers: ");         for (Integer itr : missing)             System.out.print(itr + " ");          // Print the Duplicate Number         System.out.print("\nDuplicate Numbers: ");         for (Integer itr : duplicate)             System.out.print(itr + " ");     }      // Driver code     public static void main(String args[]) {         int arr[] = { 1, 2, 2, 2, 4, 5, 7 };         int N = arr.length;         findElements(arr, N);     }  }  // This code is contributed by gfgking. 
Python3
# Python3 program for the above approach  # Function to find the duplicate and # the missing elements over the range # [1, N] def findElements(arr, N) :     i = 0;      # Stores the missing and duplicate     # numbers in the array arr[]     missing = [];     duplicate = set();      # Traverse the given array arr[]     while (i != N) :                  # Check if the current element         # is not same as the element at         # index arr[i] - 1, then swap         if (arr[i] != arr[arr[i] - 1]) :                          t = arr[i]             arr[i] = arr[arr[i] - 1]             arr[t - 1]  = t                      # Otherwise, increment the index         else :             i += 1;      # Traverse the array again     for i in range(N) :                  # If the element is not at its         # correct position         if (arr[i] != i + 1) :              # Stores the missing and the             # duplicate elements             missing.append(i + 1);             duplicate.add(arr[i]);      # Print the Missing Number     print("Missing Numbers: ",end="");          for it in missing:         print(it,end=" ");      # Print the Duplicate Number     print("\nDuplicate Numbers: ",end="");          for it in list(duplicate) :         print(it, end=' ');  # Driver code if __name__ == "__main__" :      arr = [ 1, 2, 2, 2, 4, 5, 7 ];     N = len(arr);     findElements(arr, N);      # This code is contributed by AnkThon 
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG {    // Function to find the duplicate and   // the missing elements over the range   // [1, N]   static void findElements(int[] arr, int N)   {     int i = 0;      // Stores the missing and duplicate     // numbers in the array arr[]     List<int> missing = new List<int>();     HashSet<int> duplicate = new HashSet<int>();      // Traverse the given array arr[]     while (i != N) {       // Check if the current element       // is not same as the element at       // index arr[i] - 1, then swap       if (arr[i] != arr[arr[i] - 1]) {         int temp = arr[i];         arr[i] = arr[arr[i] - 1];         arr[temp - 1] = temp;       }        // Otherwise, increment the index       else {         i++;       }     }      // Traverse the array again     for (i = 0; i < N; i++) {        // If the element is not at its       // correct position       if (arr[i] != i + 1) {          // Stores the missing and the         // duplicate elements         missing.Add(i + 1);         duplicate.Add(arr[i]);       }     }      // Print the Missing Number     Console.Write("Missing Numbers: ");     foreach(int itr in missing)       Console.Write(itr + " ");      // Print the Duplicate Number     Console.Write("\nDuplicate Numbers: ");     foreach(int itr in duplicate)       Console.Write(itr + " ");   }    // Driver code   public static void Main()   {     int[] arr = { 1, 2, 2, 2, 4, 5, 7 };     int N = arr.Length;     findElements(arr, N);   } }  // This code is contributed by ukasp. 
JavaScript
<script> // Javascript program for the above approach  // Function to find the duplicate and // the missing elements over the range // [1, N] function findElements(arr, N) {   let i = 0;    // Stores the missing and duplicate   // numbers in the array arr[]   let missing = [];   let duplicate = new Set();    // Traverse the given array arr[]   while (i != N)   {        // Check if the current element     // is not same as the element at     // index arr[i] - 1, then swap     if (arr[i] != arr[arr[i] - 1]) {       t = arr[i];       arr[i] = arr[arr[i] - 1];       arr[t - 1] = t;     }      // Otherwise, increment the index     else {       i += 1;     }   }    // Traverse the array again   for (let i = 0; i < N; i++)   {        // If the element is not at its     // correct position     if (arr[i] != i + 1)      {            // Stores the missing and the       // duplicate elements       missing.push(i + 1);       duplicate.add(arr[i]);     }   }    // Print the Missing Number   document.write("Missing Numbers: ");    for (it of missing) document.write(it + " ");    // Print the Duplicate Number   document.write("<br>Duplicate Numbers: ");    for (let it of [...duplicate]) document.write(it + " "); }  // Driver code  let arr = [1, 2, 2, 2, 4, 5, 7]; let N = arr.length; findElements(arr, N);  // This code is contributed by _saurabh_jaiswal  </script> 

Output: 
Missing Numbers: 3 6  Duplicate Numbers: 2

 

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Check if an Array is a permutation of numbers from 1 to N

A

arunbang17
Improve
Article Tags :
  • Mathematical
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Check if an Array is a permutation of numbers from 1 to N
    Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The
    15+ min read
  • Check if an Array is a permutation of numbers from 1 to N : Set 2
    Given an array arr containing N positive integers, the task is to check if the given array arr represents a permutation or not. A sequence of N integers is called a permutation if it contains all integers from 1 to N exactly once. Examples: Input: arr[] = {1, 2, 5, 3, 2} Output: No Explanation: The
    4 min read
  • Change the array into a permutation of numbers from 1 to n
    Given an array A of n elements. We need to change the array into a permutation of numbers from 1 to n using minimum replacements in the array. Examples: Input : A[] = {2, 2, 3, 3} Output : 2 1 3 4 Explanation: To make it a permutation of 1 to 4, 1 and 4 are missing from the array. So replace 2, 3 wi
    5 min read
  • Minimum cost to make an Array a permutation of first N natural numbers
    Given an array arr of positive integers of size N, the task is to find the minimum cost to make this array a permutation of first N natural numbers, where the cost of incrementing or decrementing an element by 1 is 1.Examples: Input: arr[] = {1, 1, 7, 4} Output: 5 Explanation: Perform increment oper
    4 min read
  • Find all numbers in range [1, N] that are not present in given Array
    Given an array arr[] of size N, where arr[i] is natural numbers less than or equal to N, the task is to find all the numbers in the range [1, N] that are not present in the given array. Examples: Input: arr[ ] = {5, 5, 4, 4, 2}Output: 1 3Explanation: For all numbers in the range [1, 5], 1 and 3 are
    4 min read
  • Minimum steps to convert an Array into permutation of numbers from 1 to N
    Given an array arr of length N, the task is to count the minimum number of operations to convert given sequence into a permutation of first N natural numbers (1, 2, ...., N). In each operation, increment or decrement an element by one.Examples: Input: arr[] = {4, 1, 3, 6, 5} Output: 4 Apply decremen
    4 min read
  • Find the Number of Permutations that satisfy the given condition in an array
    Given an array arr[] of size N, the task is to find the number of permutations in the array that follows the given condition: If K is the maximum element in the array, then the elements before K in the array should be in the ascending order and the elements after K in the array should be in the desc
    12 min read
  • Find sum of count of duplicate numbers in all subarrays of given array
    Given an array arr[] of size N. The task it to find the sum of count of duplicate numbers in all subarrays of given array arr[]. For example array {1, 2, 3, 2, 3, 2} has two duplicate elements (i.e, 2 and 3 come more than one time in the array). Examples:Input: N = 2, arr = {3,3}Output: 1Explanation
    6 min read
  • Find all missing numbers from a given sorted array
    Given a sorted array arr[] of N integers, The task is to find the multiple missing elements in the array between the ranges [arr[0], arr[N-1]]. Examples: Input: arr[] = {6, 7, 10, 11, 13}Output: 8 9 12 Explanation: The elements of the array are present in the range of the maximum and minimum array e
    13 min read
  • Find duplicate in an array in O(n) and by using O(1) extra space
    Given an array arr[] containing n integers where each integer is between 1 and (n-1) (inclusive). There is only one duplicate element, find the duplicate element in O(n) time complexity and O(1) space. Examples : Input : arr[] = {1, 4, 3, 4, 2} Output : 4Input : arr[] = {1, 3, 2, 1}Output : 1Approac
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences