 GeeksforGeeks App
Open App Browser
Continue

# Array elements that appear more than once

Given an integer array, print all repeating elements (Elements that appear more than once) in the array. The output should contain elements according to their first occurrences.

Examples:

```Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}
Output: 10 45

Input: arr[] = {1, 2, 3, 4, 2, 5}
Output: 2

Input: arr[] = {1, 1, 1, 1, 1}
Output: 1```

Method #1:Naive approach:

We iterate through the array using two nested loops to compare each element with every other element in the array. If an element appears more than once, we insert it into the set. The repeating variable is used to keep track of whether an element has already been inserted into the set. Once a repeating element is found, we break out of the inner loop to avoid inserting it multiple times.

Finally, we print the contents of the set to get the repeating elements in the order of their first occurrence.

Implementation:

## C++

 `#include ``using` `namespace` `std;` `void` `printRepeating(``int` `arr[], ``int` `n) {``    ``set<``int``>s;``    ``for` `(``int` `i = 0; i < n; i++) {``        ``bool` `repeating = ``false``;``        ``for` `(``int` `j = i + 1; j < n; j++) {``            ``if` `(arr[i] == arr[j]) {``                ``if` `(!repeating) {``                    ``s.insert(arr[i]);``                ``}``                ``repeating = ``true``;``                ``break``; ``// Break the inner loop once a repeating element is found``            ``}``        ``}``    ``}``    ``for``(``auto` `it:s)``    ``{``        ``cout<

Output

`10 45 `

Time Complexity:   O(n^2) .

Auxiliary Space:  O(k), where k is the number of repeating element .

Method #2:Hashing

The idea is to use Hashing to solve this in O(n) time on average. We store elements and their counts in a hash table. After storing counts, we traverse input array again and print those elements whose counts are more than once. To make sure that every output element is printed only once, we set count as 0 after printing the element.

Implementation:

## C++

 `// C++ program to print all repeating elements``#include ``using` `namespace` `std;` `void` `printRepeating(``int` `arr[], ``int` `n)``{``    ``// Store elements and their counts in``    ``// hash table``    ``unordered_map<``int``, ``int``> mp;``    ``for` `(``int` `i = 0; i < n; i++)``        ``mp[arr[i]]++;` `    ``// Since we want elements in same order,``    ``// we traverse array again and print``    ``// those elements that appear more than``    ``// once.``    ``for` `(``int` `i = 0; i < n; i++) {``        ``if` `(mp[arr[i]] > 1) {``            ``cout << arr[i] << ``" "``;` `            ``// This is tricky, this is done``            ``// to make sure that the current``            ``// element is not printed again``            ``mp[arr[i]] = 0;``        ``}``    ``}``}` `// Driver code``int` `main()``{``    ``int` `arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``printRepeating(arr, n);``    ``return` `0;``}`

## Java

 `// Java program to print all repeating elements` `import` `java.util.*;``import` `java.util.Map.Entry;``import` `java.io.*;``import` `java.lang.*;` `public` `class` `GFG {` `    ``static` `void` `printRepeating(``int` `arr[], ``int` `n)``    ``{` `        ``// Store elements and their counts in``        ``// hash table``        ``Map map``            ``= ``new` `LinkedHashMap();``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``try` `{``                ``map.put(arr[i], map.get(arr[i]) + ``1``);``            ``}``            ``catch` `(Exception e) {``                ``map.put(arr[i], ``1``);``            ``}``        ``}` `        ``// Since we want elements in the same order,``        ``// we traverse array again and print``        ``// those elements that appear more than once.` `        ``for` `(Entry e : map.entrySet()) {``            ``if` `(e.getValue() > ``1``) {``                ``System.out.print(e.getKey() + ``" "``);``            ``}``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) ``throws` `IOException``    ``{``        ``int` `arr[] = { ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `};``        ``int` `n = arr.length;``        ``printRepeating(arr, n);``    ``}``}` `// This code is contributed by Wrick`

## Python3

 `# Python3 program to print``# all repeating elements``def` `printRepeating(arr, n):` `    ``# Store elements and``    ``# their counts in``    ``# hash table``    ``mp ``=` `[``0``] ``*` `100``    ``for` `i ``in` `range``(``0``, n):``        ``mp[arr[i]] ``+``=` `1` `    ``# Since we want elements``    ``# in same order, we``    ``# traverse array again``    ``# and print those elements``    ``# that appear more than once.``    ``for` `i ``in` `range``(``0``, n):``        ``if` `(mp[arr[i]] > ``1``):``            ``print``(arr[i], end ``=` `" "``)``            ` `            ``# This is tricky, this``            ``# is done to make sure``            ``# that the current element``            ``# is not printed again``            ``mp[arr[i]] ``=` `0``    ` `# Driver code``arr ``=` `[``12``, ``10``, ``9``, ``45``,``       ``2``, ``10``, ``10``, ``45``]``n ``=` `len``(arr)``printRepeating(arr, n)` `# This code is contributed``# by Smita`

## C#

 `// C# program to print all repeating elements``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{``static` `void` `printRepeating(``int` `[]arr, ``int` `n)``{` `    ``// Store elements and their counts in``    ``// hash table``    ``Dictionary<``int``,``               ``int``> map = ``new` `Dictionary<``int``,``                                         ``int``>();``    ``for` `(``int` `i = 0 ; i < n; i++)``    ``{``        ``if``(map.ContainsKey(arr[i]))``        ``{``            ``var` `val = map[arr[i]];``            ``map.Remove(arr[i]);``            ``map.Add(arr[i], val + 1);``        ``}``        ``else``        ``{``            ``map.Add(arr[i], 1);``        ``}``    ``}` `    ``// Since we want elements in the same order,``    ``// we traverse array again and print``    ``// those elements that appear more than once.``    ``foreach``(KeyValuePair<``int``, ``int``> e ``in` `map)``    ``{``        ``if` `(e.Value > 1)``        ``{``            ``Console.Write(e.Key + ``" "``);``        ``}``    ``}``}` `// Driver code``public` `static` `void` `Main(String[] args)``{``    ``int` `[]arr = { 12, 10, 9, 45, 2, 10, 10, 45 };``    ``int` `n = arr.Length;``    ``printRepeating(arr, n);``}``}` `// This code is contributed by PrinciRaj1992`

## Javascript

 `// JavaScript program to print all``// repeating elements` `function` `printRepeating(arr, n)``{``    ``// Store elements and their counts in``    ``// hash table``    ``var` `mp = ``new` `Map();``    ``for` `(``var` `i = 0; i < n; i++)``    ``{``        ``if``(mp.has(arr[i]))``            ``mp.set(arr[i], mp.get(arr[i])+1)``        ``else`   `            ``mp.set(arr[i], 1)``    ``}` `    ``// Since we want elements in same order,``    ``// we traverse array again and print``    ``// those elements that appear more than``    ``// once.``    ``for` `(``var` `i = 0; i < n; i++) {``        ``if` `(mp.get(arr[i]) > 1) {``            ``console.log( arr[i] + ``" "``);` `            ``// This is tricky, this is done``            ``// to make sure that the current``            ``// element is not printed again``            ``mp.set(arr[i], 0);``        ``}``    ``}``}` `// Driver code``var` `arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];``var` `n = arr.length;``printRepeating(arr, n);`

Output

`10 45 `

complexity Analysis:

• Time Complexity: O(n) under the assumption that hash insert and search functions work in O(1) time.
• Auxiliary Space: O(n), where n represents the size of the given array.

#### Method #3:Using Built-in Python functions:

• Count all the frequencies of all elements using Counter() function.
• Traverse in this frequency dictionary and print all keys whose value is greater than 1.

Below is the implementation of above approach:

## C++

 `// C++ program to print``// all repeating elements` `#include ``#include ` `using` `namespace` `std;` `void` `printRepeating(``int` `arr[], ``int` `n)``{``    ``// Create an unordered_map to store the frequency of``    ``// each element``    ``unordered_map<``int``, ``int``> freq;` `    ``// Traverse the array and increment the count of each``    ``// element in the map``    ``for` `(``int` `i = 0; i < n; i++) {``        ``freq[arr[i]]++;``    ``}` `    ``// Traverse the map and print all the keys whose value``    ``// is greater than 1``    ``for` `(``auto` `i : freq) {``        ``if` `(i.second > 1) {``            ``cout << i.first << ``" "``;``        ``}``    ``}``}` `int` `main()``{``    ``int` `arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``printRepeating(arr, n);``    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {``    ``public` `static` `void` `printRepeating(``int``[] arr, ``int` `n)``    ``{``        ``// Counting frequencies``        ``Map freq``            ``= ``new` `HashMap();``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``int` `key = arr[i];``            ``freq.put(key, freq.getOrDefault(key, ``0``) + ``1``);``        ``}` `        ``// Traverse the freq dictionary and print all the``        ``// keys whose value is greater than 1``        ``for` `(``int` `i : freq.keySet()) {``            ``if` `(freq.get(i) > ``1``) {``                ``System.out.print(i + ``" "``);``            ``}``        ``}``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``int``[] arr = { ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `};``        ``int` `n = arr.length;``        ``printRepeating(arr, n);``    ``}``}`

## Python3

 `# Python3 program to print``# all repeating elements``from` `collections ``import` `Counter` `def` `printRepeating(arr, n):``  ` `    ``# Counting frequencies``    ``freq ``=` `Counter(arr)``    ` `    ``# Traverse the freq dictionary and``    ``# print all the keys whose value``    ``# is greater than 1``    ``for` `i ``in` `freq:``        ``if``(freq[i] > ``1``):``            ``print``(i, end``=``" "``)`  `# Driver code``arr ``=` `[``12``, ``10``, ``9``, ``45``,``       ``2``, ``10``, ``10``, ``45``]``n ``=` `len``(arr)``printRepeating(arr, n)` `# This code is contributed by vikkycirus`

## C#

 `using` `System;``using` `System.Collections.Generic;` `public` `class` `Program {``  ``public` `static` `void` `printRepeating(``int``[] arr, ``int` `n)``  ``{` `    ``// Counting frequencies``    ``Dictionary<``int``, ``int``> freq = ``new` `Dictionary<``int``, ``int``>();``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int` `key = arr[i];``      ``if` `(freq.ContainsKey(key)) {``        ``freq[key]++;``      ``} ``else` `{``        ``freq[key] = 1;``      ``}``    ``}` `    ``// Traverse the freq dictionary and print all the``    ``// keys whose value is greater than 1``    ``foreach` `(``int` `i ``in` `freq.Keys) {``      ``if` `(freq[i] > 1) {``        ``Console.Write(i + ``" "``);``      ``}``    ``}``  ``}` `  ``public` `static` `void` `Main() {``    ``int``[] arr = {12, 10, 9, 45, 2, 10, 10, 45};``    ``int` `n = arr.Length;``    ``printRepeating(arr, n);``  ``}``}`

## Javascript

 `// Function to print all repeating elements``function` `printRepeating(arr, n) {``    ``// Counting frequencies``    ``let freq = {};``    ``for` `(let i = 0; i < n; i++) {``        ``if` `(freq[arr[i]] === undefined) {``            ``freq[arr[i]] = 1;``        ``} ``else` `{``            ``freq[arr[i]]++;``        ``}``    ``}` `    ``// Traverse the freq dictionary and``    ``// print all the keys whose value``    ``// is greater than 1``    ``for` `(let key ``in` `freq) {``        ``if` `(freq[key] > 1) {``            ``console.log(key);``        ``}``    ``}``}` `// Driver code``let arr = [12, 10, 9, 45,``           ``2, 10, 10, 45];``let n = arr.length;``printRepeating(arr, n);`

Output

`10 45 `

complexity Analysis:

• Auxiliary Space: O(n), where n represents the size of the given array.

Method #4(Space Optimization) : we can use binary search lower_bound function to find first occurrence of arr[i] and Upper_bound function to find last occurrence of x and if the last_index-first_ind+1>1 means , arr[i] has more than one frequency.

Below is the implementation of above approach:

## C++

 `// C++ implementation of the above approach` `#include ``using` `namespace` `std;` `//Function to Print elements that repeat more than 1``void` `printRepeating(``int` `arr[], ``int` `n)``{   sort(arr,arr+n);``//sort array for binary search``     ` `    ``for``(``int` `i=0;i 1 )``// elements that repeat more than 1``      ``{  i=last_index; ``//update i to last_index ``       ``cout<

## Java

 `import` `java.util.*;` `class` `Main {``    ``// Function to Print elements that repeat more than 1``    ``public` `static` `void` `printRepeating(``int` `arr[], ``int` `n)``    ``{``        ``Arrays.sort(arr);``//sort array for binary search` `        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``// index of first and last occ of arr[i];``            ``int` `first_index = Arrays.binarySearch(arr, arr[i]);``            ``int` `last_index = Arrays.binarySearch(arr, arr[i]);` `            ``// to handle the case if the element is not found``            ``if` `(first_index < ``0``) {``                ``continue``;``            ``}` `            ``while` `((last_index < n - ``1``) && (arr[last_index + ``1``] == arr[i])) {``                ``last_index++;``            ``}` `            ``int` `fre = last_index - first_index + ``1``;``//frequency of arr[i]` `            ``if` `(fre > ``1``)``// elements that repeat more than 1``            ``{``                ``i = last_index; ``// update i to last_index``                ``System.out.print(arr[i] + ``" "``); ``// print repeat element``            ``}``        ``}``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `};``        ``int` `n = arr.length;` `        ``// Function call``        ``printRepeating(arr, n);``    ``}``}`

## Python3

 `# Python implementation``def` `printRepeating(arr, n):``    ` `    ``# Sort the array so that repeating ``    ``# elements can be tracked``    ``arr.sort()``      ` `    ``# Initialize index = 0``    ``i ``=` `0``    ``while` `i < n:``        ``first_index ``=` `i``          ` `        ``# Initialize last_index to i``        ``# plus the frequency``        ``last_index ``=` `i ``+` `arr.count(arr[i]) ``-` `1``          ` `        ``# If frequency of current element ``        ``# is more than 1, then print it ``        ``if` `last_index ``-` `first_index > ``0``:``            ``print``(arr[i], end ``=` `" "``)``          ` `        ``# Update index to last index ``        ``# plus 1``        ``i ``=` `last_index ``+` `1``        ` `arr ``=` `[ ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `]``n ``=` `len``(arr)` `# Function call``printRepeating(arr, n)` `# This code is contributed by akashish__`

## Javascript

 `function` `printRepeating(arr, n) {``  ``// Sort the array so that repeating elements can be tracked``  ``arr.sort();` `  ``// Initialize index = 0``  ``let i = 0;``  ``while` `(i < n) {``    ``let first_index = i;` `    ``// Initialize last_index to i plus the frequency``    ``let last_index = i + arr.filter(x => x === arr[i]).length - 1;` `    ``// If frequency of current element is more than 1, then print it``    ``if` `(last_index - first_index > 0) {``      ``console.log(arr[i]);``    ``}` `    ``// Update index to last index plus 1``    ``i = last_index + 1;``  ``}``}` `let arr = [12, 10, 9, 45, 2, 10, 10, 45];``let n = arr.length;` `// Function call``printRepeating(arr, n);`

## C#

 `using` `System;``using` `System.Linq;` `class` `GFG {``  ` `    ``// Function to Print elements that``    ``// repeat more than 1``    ``static` `void` `printRepeating(``int``[] arr, ``int` `n)``    ``{``        ``// sort array for binary search``        ``Array.Sort(arr);` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``// index of first and last``            ``// occ of arr[i];``            ``int` `first_index``                ``= Array.BinarySearch(arr, arr[i]);``            ``int` `last_index = Array.LastIndexOf(arr, arr[i]);` `            ``// frequency of arr[i]``            ``int` `fre = last_index - first_index + 1;``            ``// elements that repeat more than 1``            ``if` `(fre > 1) {``                ``// update i to last_index``                ``i = last_index;` `                ``// print repeat element``                ``Console.Write(arr[i] + ``" "``);``            ``}``        ``}``    ``}` `    ``// Driver code``    ``static` `void` `Main()``    ``{``        ``int``[] arr = { 12, 10, 9, 45, 2, 10, 10, 45 };``        ``int` `n = arr.Length;` `        ``// Function call``        ``printRepeating(arr, n);``    ``}``}`

Output

`10 45 `

Time Complexity: O(n*log2n), Take log2n for binary search function(upper and lower bound)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up