Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Find duplicates in O(n) time and O(n) extra space
Next article icon

Find duplicates in O(n) time and O(n) extra space

Last Updated : 24 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.

Note: The repeating element should be printed only once.

Example: 

Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]
Output: 1, 3, 6
Explanation: The numbers 1 , 3 and 6 appears more than once in the array.

Input : n = 5, arr[] = [1, 2, 3, 4 ,3]
Output: 3
Explanation: The number 3 appears more than once in the array.

This problem is an extended version of the following problem Find the two repeating elements in a given array.

Table of Content

  • Using hashmap - O(n) Time and O(n) Space
  • Using Auxiliary Array - O(n) Time and O(n) Space

Using hashmap - O(n) Time and O(n) Space

To find duplicates in an array, start by creating an empty hashmap to track the frequency of each element. Iterate through the array, updating the frequency count for each element in the hashmap. Then, iterate through the hashmap and add any element with a frequency greater than 1 to the result. If no duplicates are found add -1 to the result. Finally, return the result containing either the duplicate elements or -1 if no duplicates were found.

C++
// C++ code to find duplicates in an array // using hashmap  #include <bits/stdc++.h> using namespace std;  vector<int> findDuplicates(vector<int> &arr) {      // Step 1: Create an empty unordered map to store     // element frequencies     int n = arr.size();     unordered_map<int, int> freqMap;     vector<int> result;      // Step 2: Iterate through the array and count     // element frequencies     for (int i = 0; i < n; i++) {         freqMap[arr[i]]++;     }      // Step 3: Iterate through the hashmap to find duplicates     for (auto &entry : freqMap) {         if (entry.second > 1) {             result.push_back(entry.first);         }     }      // Step 4: If no duplicates found, add -1 to the result     if (result.empty()) {         result.push_back(-1);     }      // Step 6: Return the result vector containing     // duplicate elements or -1     return result; }  int main() {     vector<int> arr = {1, 6, 5, 2, 3, 3, 2};      vector<int> duplicates = findDuplicates(arr);      for (int element : duplicates) {         cout << element << " ";     }      return 0; } 
Java
// Java code to find duplicates in an array // using hashmap  import java.util.*;  class GfG {      static List<Integer> findDuplicates(Integer[] arr) {          // Step 1: Create an empty hashmap to store         // element frequencies         int n = arr.length;         Map<Integer, Integer> freqMap = new HashMap<>();         List<Integer> result = new ArrayList<>();          // Step 2: Iterate through the array and         // count element frequencies         for (int i = 0; i < n; i++) {             freqMap.put(arr[i],                         freqMap.getOrDefault(arr[i], 0)                             + 1);         }          // Step 3: Iterate through the hashmap to find         // duplicates         for (Map.Entry<Integer, Integer> entry :              freqMap.entrySet()) {             if (entry.getValue() > 1) {                 result.add(entry.getKey());             }         }          // Step 4: If no duplicates found, add -1 to the         // result         if (result.isEmpty()) {             result.add(-1);         }          // Step 6: Return the result list containing         // duplicate elements or -1         return result;     }      public static void main(String[] args) {          Integer[] arr = { 1, 6, 5, 2, 3, 3, 2 };         List<Integer> duplicates = findDuplicates(arr);          for (int element : duplicates) {             System.out.print(element + " ");         }     } } 
Python
# Python code to find duplicates in an array # using hashmap  def findDuplicates(arr):        # Step 1: Create an empty dictionary     # to store element frequencies     freqMap = {}     result = []      # Step 2: Iterate through the array and     # count element frequencies     for num in arr:         freqMap[num] = freqMap.get(num, 0) + 1      # Step 3: Iterate through the dictionary to     # find duplicates     for key, value in freqMap.items():         if value > 1:             result.append(key)      # Step 4: If no duplicates found, add -1 to the result     if not result:         result.append(-1)      # Step 6: Return the result list containing     # duplicate elements or -1     return result   if __name__ == "__main__":     arr = [1, 6, 5, 2, 3, 3, 2]     duplicates = findDuplicates(arr)      for element in duplicates:         print(element, end=" ") 
C#
// C# code to find duplicates in an array // using hashmap  using System; using System.Collections.Generic;  class GfG {      static List<int> findDuplicates(int[] arr) {          // Step 1: Create an empty dictionary to         // store element frequencies         int n = arr.Length;         Dictionary<int, int> freqMap             = new Dictionary<int, int>();         List<int> result = new List<int>();          // Step 2: Iterate through the array and         // count element frequencies         for (int i = 0; i < n; i++) {             if (freqMap.ContainsKey(arr[i])) {                 freqMap[arr[i]]++;             }             else {                 freqMap[arr[i]] = 1;             }         }          // Step 3: Iterate through the dictionary         // to find duplicates         foreach(var entry in freqMap) {             if (entry.Value > 1) {                 result.Add(entry.Key);             }         }          // Step 4: If no duplicates found, add -1 to the         // result         if (result.Count == 0) {             result.Add(-1);         }          // Step 6: Return the result list containing         // duplicate elements or -1         return result;     }      static void Main(string[] args) {         int[] arr = new int[] { 1, 6, 5, 2, 3, 3, 2 };         List<int> duplicates = findDuplicates(arr);          foreach(int element in duplicates) {             Console.Write(element + " ");         }     } } 
JavaScript
// JavaScript code to find duplicates in an array // using hashmap  function findDuplicates(arr) {      // Step 1: Create an empty object to store      // element frequencies     const freqMap = {};     const result = [];      // Step 2: Iterate through the array and      // count element frequencies     for (let num of arr) {         freqMap[num] = (freqMap[num] || 0) + 1;     }      // Step 3: Iterate through the object to find duplicates     for (let key in freqMap) {         if (freqMap[key] > 1) {             result.push(parseInt(key));         }     }      // Step 4: If no duplicates found, add -1 to the result     if (result.length === 0) {         result.push(-1);     }      // Step 6: Return the result array containing      // duplicate elements or -1     return result; }  // Driver code const arr = [1, 6, 5, 2, 3, 3, 2]; const duplicates = findDuplicates(arr);  console.log(duplicates.join(' ')); 

Output
3 2 

Using Auxiliary Array - O(n) Time and O(n) Space

Since the numbers inside the array range from 0 to n-1 (inclusive), where n is the length of the array, we can utilize an auxiliary array of size n to record the frequency of each element. By iterating through we can found the duplicates easily.

C++
// C++ code to find duplicates in an array // using auxilary array  #include <bits/stdc++.h> using namespace std;  vector<int> findDuplicates(vector<int> &arr) {      int n = arr.size();     vector<int> freqArr(n);     vector<int> result;      // Step 2: Iterate through the array and count     // element frequencies     for (int i = 0; i < n; i++) {         freqArr[arr[i]]++;     }      // Step 3: Iterate through all the possible elements to check     // duplicates     for (int i = 0; i < n; i++) {         if (freqArr[i] > 1) {             result.push_back(i);         }     }      // Step 4: If no duplicates found, add -1 to the result     if (result.empty()) {         result.push_back(-1);     }      // Step 6: Return the result vector containing     // duplicate elements or -1     return result; }  int main() {     vector<int> arr = {1, 6, 5, 2, 3, 3, 2};      vector<int> duplicates = findDuplicates(arr);      for (int element : duplicates) {         cout << element << " ";     }      return 0; } 
Java
// Java code to find duplicates in an array // using auxiliary array  import java.util.*;  class GfG {      static int[] findDuplicates(int[] arr) {          int n = arr.length;         int[] freqArr = new int[n];          List<Integer> result = new ArrayList<>();          // Step 2: Iterate through the array         // and count element frequencies         for (int i = 0; i < n; i++) {             freqArr[arr[i]]++;         }          // Step 3: Iterate through all the possible         // elements to check duplicates         for (int i = 0; i < n; i++) {             if (freqArr[arr[i]] > 1) {                 result.add(arr[i]);                 freqArr[arr[i]]                     = 0; // To avoid adding duplicates again             }         }          // Step 4: If no duplicates found, add -1 to the         // result         if (result.isEmpty()) {             result.add(-1);         }          // Convert the result list to an array and return         return result.stream().mapToInt(i -> i).toArray();     }      public static void main(String[] args) {          int[] arr = { 1, 6, 5, 2, 3, 3, 2 };         int[] duplicates = findDuplicates(arr);          for (int element : duplicates) {             System.out.print(element + " ");         }     } } 
Python
# Python code to find duplicates in an array # using auxiliary array   def findDuplicates(arr):     n = len(arr)     freqArr = [0] * n     result = []      # Step 2: Iterate through the array and     # count element frequencies     for num in arr:         freqArr[num] += 1      # Step 3: Iterate through all the possible     # elements to check duplicates     for i in range(n):         if freqArr[i] > 1:             result.append(i)      # Step 4: If no duplicates found,     # add -1 to the result     if not result:         result.append(-1)      # Step 6: Return the result list containing      # duplicate elements or -1     return result   if __name__ == "__main__":     arr = [1, 6, 5, 2, 3, 3, 2]     duplicates = findDuplicates(arr)      for element in duplicates:         print(element, end=" ") 
C#
// C# code to find duplicates in an array // using auxiliary array  using System; using System.Collections.Generic;  class GfG {      static int[] findDuplicates(int[] arr) {          int n = arr.Length;         int[] freqArr = new int[n];         List<int> result = new List<int>();          // Step 2: Iterate through the array and count         // element frequencies         for (int i = 0; i < n; i++) {             freqArr[arr[i]]++;         }          // Step 3: Iterate through all the possible elements         // to check duplicates         for (int i = 0; i < n; i++) {             if (freqArr[arr[i]] > 1) {                 result.Add(arr[i]);                 freqArr[arr[i]]                     = 0;             }         }          // Step 4: If no duplicates found, add -1 to the         // result         if (result.Count == 0) {             result.Add(-1);         }          // Step 6: Return the result list containing         // duplicate elements or -1         return result.ToArray();     }      static void Main(string[] args) {          int[] arr = { 1, 6, 5, 2, 3, 3, 2 };         int[] duplicates = findDuplicates(arr);          foreach(int element in duplicates) {             Console.Write(element + " ");         }     } } 
JavaScript
// JavaScript code to find duplicates in an array // using auxiliary array  function findDuplicates(arr) {      const n = arr.length;     const freqArr = new Array(n).fill(0);     const result = [];      // Step 2: Iterate through the array and count element     // frequencies     for (const num of arr) {         freqArr[num]++;     }      // Step 3: Iterate through all the possible elements to     // check duplicates     for (let i = 0; i < n; i++) {         if (freqArr[i] > 1) {             result.push(i);         }     }      // Step 4: If no duplicates found, add -1 to the result     if (result.length === 0) {         result.push(-1);     }      // Step 6: Return the result array containing duplicate     // elements or -1     return result; }  // Driver code const arr = [ 1, 6, 5, 2, 3, 3, 2 ]; const duplicates = findDuplicates(arr); console.log(duplicates.join(" ")); 

Output
2 3 

All of the above approaches require extra space. Please refer to Duplicates in an array in O(n) and by using O(1) extra space.


Next Article
Find duplicates in O(n) time and O(n) extra space

K

kartik
Improve
Article Tags :
  • DSA
  • Arrays
  • Amazon
  • Qualcomm
  • Paytm
  • Zoho
Practice Tags :
  • Amazon
  • Paytm
  • Qualcomm
  • Zoho
  • Arrays

Similar Reads

    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 : 1Approach
    13 min read
    Duplicates in an array in O(n) and by using O(1) extra space
    Given an array arr[] of n elements that contains elements from 0 to n-1, with any of these numbers appearing any number of times. The task is to find the repeating numbers.Note: The repeating element should be printed only once.Example: Input: n = 7, arr[] = [1, 2, 3, 6, 3, 6, 1]Output: 1, 3, 6Expla
    5 min read
    Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
    Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeatin
    10 min read
    Find maximum in a stack in O(1) time and O(1) extra space
    Given a stack of integers. The task is to design a special stack such that the maximum element can be found in O(1) time and O(1) extra space.Examples: Input: operations = [push(2), push(3), peek(), pop(), getMax(), push(1), getMax()]Output: [3, 2, 2]Explanation: push(2): Stack is [2]push(3): Stack
    10 min read
    Find duplicates in constant array with elements 0 to N-1 in O(1) space
    Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is
    12 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