Duplicates in an array in O(n) and by using O(1) extra space | Set-2 - GeeksforGeeks

02 Sep, 2021
Given an array of n elements containing 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.
Example:
Input: n = 7 , array = {1, 2, 3, 1, 3, 6, 6}
Output: 1, 3 and 6.
Explanation: Duplicate element in the array are 1 , 3 and 6

Input: n = 6, array = {5, 3, 1, 3, 5, 5}
Output: 3 and 5.
Explanation: Duplicate element in  the array are 3 and 6
We have discussed an approach for this question in the below post: Duplicates in an array in O(n) and by using O(1) extra space | Set-2. But there is a problem in the above approach. It prints the repeated number more than once.
Approach: The basic idea is to use a HashMap to solve the problem. But there is a catch, the numbers in the array are from 0 to n-1, and the input array has length n. So, the input array can be used as a HashMap. While traversing the array, if an element a is encountered then increase the value of a%n‘th element by n. The frequency can be retrieved by dividing the a%n‘th element by n.
Algorithm:  
Traverse the given array from start to end.For every element in the array increment the arr[i]%n‘th element by n.Now traverse the array again and print all those indices i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that index.
Traverse the given array from start to end.
For every element in the array increment the arr[i]%n‘th element by n.
Now traverse the array again and print all those indices i for which arr[i]/n is greater than 1. Which guarantees that the number n has been added to that index.
Note: This approach works because all elements are in the range from 0 to n-1 and arr[i]/n would be greater than 1 only if a value “i” has appeared more than once. 
Below is the implementation of the above approach:
CPP
Java
Python3
C#
PHP
Javascript
// C++ program to print all elements that// appear more than once.#include <iostream>using namespace std; // function to find repeating elementsvoid printRepeating(int arr[], int n){    // First check all the values that are    // present in an array then go to that    // values as indexes and increment by    // the size of array    for (int i = 0; i < n; i++)    {        int index = arr[i] % n;        arr[index] += n;    }     // Now check which value exists more    // than once by dividing with the size    // of array    for (int i = 0; i < n; i++)    {        if ((arr[i] / n) >= 2)            cout << i << " ";    }} // Driver codeint main(){    int arr[] = { 1, 6, 3, 1, 3, 6, 6 };    int arr_size = sizeof(arr) / sizeof(arr[0]);     cout << "The repeating elements are: \n";     // Function call    printRepeating(arr, arr_size);    return 0;}
// Java program to print all elements that// appear more than once.import java.util.*;class GFG {     // function to find repeating elements    static void printRepeating(int arr[], int n)    {        // First check all the values that are        // present in an array then go to that        // values as indexes and increment by        // the size of array        for (int i = 0; i < n; i++)        {            int index = arr[i] % n;            arr[index] += n;        }         // Now check which value exists more        // than once by dividing with the size        // of array        for (int i = 0; i < n; i++)        {            if ((arr[i] / n) >= 2)                System.out.print(i + " ");        }    }     // Driver code    public static void main(String args[])    {        int arr[] = { 1, 6, 3, 1, 3, 6, 6 };        int arr_size = arr.length;         System.out.println("The repeating elements are: ");         // Function call        printRepeating(arr, arr_size);    }}
# Python3 program to# print all elements that# appear more than once. # function to find# repeating elements  def printRepeating(arr, n):     # First check all the        # values that are    # present in an array        # then go to that    # values as indexes        # and increment by    # the size of array    for i in range(0, n):        index = arr[i] % n        arr[index] += n     # Now check which value        # exists more    # than once by dividing        # with the size    # of array    for i in range(0, n):        if (arr[i]/n) >= 2:            print(i, end=" ")  # Driver codearr = [1, 6, 3, 1, 3, 6, 6]arr_size = len(arr) print("The repeating elements are:") # Function callprintRepeating(arr, arr_size) # This code is contributed# by Shreyanshi Arun.
// C# program to print all elements that// appear more than once. using System;class GFG {     // function to find repeating elements    static void printRepeating(int[] arr, int n)    {        // First check all the values that are        // present in an array then go to that        // values as indexes and increment by        // the size of array        for (int i = 0; i < n; i++)        {            int index = arr[i] % n;            arr[index] += n;        }         // Now check which value exists more        // than once by dividing with the size        // of array        for (int i = 0; i < n; i++)        {            if ((arr[i] / n) >= 2)                Console.Write(i + " ");        }    }     // Driver code    public static void Main()    {        int[] arr = { 1, 6, 3, 1, 3, 6, 6 };        int arr_size = arr.Length;         Console.Write("The repeating elements are: "                      + "\n");         // Function call        printRepeating(arr, arr_size);    }}
<?php// PHP program to print all// elements that appear more// than once. // function to find// repeating elementsfunction printRepeating( $arr, $n){    // First check all the values    // that are present in an array    // then go to that values as indexes    // and increment by the size of array    for ($i = 0; $i < $n; $i++)    {        $index = $arr[$i] % $n;        $arr[$index] += $n;    }     // Now check which value    // exists more than once    // by dividing with the    // size of array    for ($i = 0; $i < $n; $i++)    {        if (($arr[$i] / $n) >= 2)            echo $i , " ";    }} // Driver code$arr = array(1, 6, 3, 1, 3, 6, 6);$arr_size = sizeof($arr) /            sizeof($arr[0]); echo "The repeating elements are: \n"; // Function callprintRepeating( $arr, $arr_size); // This code is contributed by nitin mittal.?>
<script> // Javascript program to print all elements that// appear more than once.            // function to find repeating elements    function printRepeating(arr,n)    {        // First check all the values that are        // present in an array then go to that        // values as indexes and increment by        // the size of array        for (let i = 0; i < n; i++)        {            let index = arr[i] % n;            arr[index] += n;        }          // Now check which value exists more        // than once by dividing with the size        // of array        for (let i = 0; i < n; i++)        {            if ((arr[i] / n) >= 2)                document.write(i + " ");        }    }         // Driver code    let arr=[1, 6, 3, 1, 3, 6, 6];    let arr_size = arr.length;    document.write("The repeating elements are: <br>");         // Function call    printRepeating(arr, arr_size);         //  This code is contributed by avanitrachhadiya2155     </script>
The repeating elements are: 
1 3 6 
Complexity Analysis: 
Time Complexity: O(n). Only two traversals are needed. So the time complexity is O(n)
Auxiliary Space: O(1). As no extra space is needed, so the space complexity is constant
This article is contributed by Sahil Chhabra (akku). 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
Kirti_Mangal
ukasp
andrew1234
mvishnu701
Santhosh220897
avanitrachhadiya2155
imposter22
Arrays
Arrays
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
Linear Search
Linked List vs Array
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array