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

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 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.

We strongly recommend that you click here and practice it, before moving on to the solution.

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:  



  1. Traverse the given array from start to end.
  2. For every element in the array increment the arr[i]%n‘th element by n.
  3. 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print all elements that
// appear more than once.
#include <iostream>
using namespace std;
 
// function to find repeating elements
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)
            cout << i << " ";
    }
}
 
// Driver code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.println(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);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 code
arr = [1, 6, 3, 1, 3, 6, 6]
arr_size = len(arr)
 
print("The repeating elements are:")
 
# Function call
printRepeating(arr, arr_size)
 
# This code is contributed
# by Shreyanshi Arun.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP 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 ($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 call
printRepeating( $arr, $arr_size);
 
// This code is contributed by nitin mittal.
?>

chevron_right


Output

The repeating elements are: 
1 3 6 

Complexity Analysis: 

  • Time Complexity: O(n). 
    Only two traversal is 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 contribute.geeksforgeeks.org or mail your article to contribute@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 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


36


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.