Find duplicates in an Array with values 1 to N using counting sort - GeeksforGeeks

04 Apr, 2022
Given a constant array of N elements which contain elements from 1 to N – 1, with any of these numbers appearing any number of times.Examples:  
Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explanation: 3 is the number occurring more than once.  
 
Naive Approach: The naive method is to first sort the given array and then look for adjacent positions of the array to find the duplicate number. Time Complexity: O(N*log N) Auxiliary Space: O(1)Efficient Approach: To optimize the above method the idea is to use the concept of Counting Sort. Since the range of elements in the array is known, hence we could use this sorting technique to improvise the time complexity. The idea is to initialize another array(say count[]) with the same size N and initialize all the elements as 0. Then count the occurrences of each element of the array and update the count in the count[]. Print all the element whose count is greater than 1.Below is the implementation of above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the duplicate// number using counting sort methodint findDuplicate(int arr[], int n){    int countArr[n + 1], i;     // Initialize all the elements    // of the countArr to 0    for (i = 0; i <= n; i++)        countArr[i] = 0;     // Count the occurences of each    // element of the array    for (i = 0; i <= n; i++)        countArr[arr[i]]++;     bool a = false;     // Find the element with more    // than one count    for (i = 1; i <= n; i++) {         if (countArr[i] > 1) {            a = true;            cout << i << ' ';        }    }     // If unique elements are ther    // print "-1"    if (!a)        cout << "-1";} // Driver Codeint main(){    // Given N    int n = 4;     // Given array arr[]    int arr[] = { 1, 3, 4, 2, 2 };     // Function Call    findDuplicate(arr, n);    return 0;}
// Java program for the above approachimport java.util.*; class GFG {     // Function to find the duplicate number    // using counting sort method    public static int    findDuplicate(int arr[], int n)    {        int countArr[] = new int[n + 1], i;         // Initialize all the elements of the        // countArr to 0        for (i = 0; i <= n; i++)            countArr[i] = 0;         // Count the occurences of each        // element of the array        for (i = 0; i <= n; i++)            countArr[arr[i]]++;         bool a = false;         // Find the element with more        // than one count        for (i = 1; i <= n; i++) {             if (countArr[i] > 1) {                a = true;                System.out.print(i + " ");            }        }        if (!a)            System.out.println("-1");    }     // Driver Code    public static void main(String[] args)    {        int n = 4;        int arr[] = { 1, 3, 4, 2, 2 };         // Function Call        findDuplicate(arr, n);    }}
# Python3 program for the above approach # Function to find the duplicate# number using counting sort methoddef findDuplicate(arr, n):     # Initialize all the elements    # of the countArr to 0    countArr = [0] * (n + 1)     # Count the occurences of each    # element of the array    for i in range(n + 1):        countArr[arr[i]] += 1     a = False     # Find the element with more    # than one count    for i in range(1, n + 1):        if(countArr[i] > 1):            a = True            print(i, end = " ")     # If unique elements are there    # print "-1"    if(not a):        print(-1) # Driver codeif __name__ == '__main__':     # Given N    n = 4     # Given array arr[]    arr = [ 1, 3, 4, 2, 2 ]     # Function Call    findDuplicate(arr, n) # This code is contributed by Shivam Singh
// C# program for the above approachusing System; class GFG{ // Function to find the duplicate number// using counting sort methodstatic void findDuplicate(int []arr, int n){    int []countArr = new int[n + 1];    int i;     // Initialize all the elements of the    // countArr to 0    for(i = 0; i <= n; i++)       countArr[i] = 0;     // Count the occurences of each    // element of the array    for(i = 0; i <= n; i++)       countArr[arr[i]]++;     bool a = false;     // Find the element with more    // than one count    for(i = 1; i <= n; i++)    {       if (countArr[i] > 1)       {           a = true;           Console.Write(i + " ");        }    }    if (!a)        Console.WriteLine("-1");} // Driver Codepublic static void Main(String[] args){    int n = 4;    int []arr = { 1, 3, 4, 2, 2 };     // Function Call    findDuplicate(arr, n);}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach     // Function to find the duplicate number    // using counting sort method    function    findDuplicate(arr, n)    {        let countArr = Array.from({length: n+1}, (_, i) => 0), i;         // Initialize all the elements of the        // countArr to 0        for (i = 0; i <= n; i++)            countArr[i] = 0;         // Count the occurences of each        // element of the array        for (i = 0; i <= n; i++)            countArr[arr[i]]++;         let a = false;         // Find the element with more        // than one count        for (i = 1; i <= n; i++) {             if (countArr[i] > 1) {                a = true;                document.write(i + " ");            }        }        if (!a)            document.write("-1");    } // Driver Code         let n = 4;        let arr = [ 1, 3, 4, 2, 2 ];         // Function Call        findDuplicate(arr, n); </script>
2
 
Time Complexity: O(N) Auxiliary Space: O(N)Related articles:  
Find duplicates in O(n) time and O(1) extra space | Set 1Duplicates in an array in O(n) and by using O(1) extra space | Set-2
Find duplicates in O(n) time and O(1) extra space | Set 1
Duplicates in an array in O(n) and by using O(1) extra space | Set-2
 
SHIVAMSINGH67
amit143katiyar
susmitakundugoaldanga
gulshankumarar231
rajat garg
counting-sort
Arrays
Competitive Programming
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming