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
Array elements that appear more than once using 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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 ;
}
}
}
for ( auto it : s) {
cout << it << " " ;
}
}
int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof (arr) / sizeof (arr[0]);
printRepeating(arr, n);
return 0;
}
|
Java
import java.util.HashSet;
public class Main {
public static void printRepeating( int [] arr, int n) {
HashSet<Integer> set = new HashSet<>();
for ( int i = 0 ; i < n; i++) {
boolean repeating = false ;
for ( int j = i + 1 ; j < n; j++) {
if (arr[i] == arr[j]) {
if (!repeating) {
set.add(arr[i]);
}
repeating = true ;
break ;
}
}
}
for ( int value : set) {
System.out.print(value + " " );
}
}
public static void main(String[] args) {
int [] arr = { 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 };
int n = arr.length;
printRepeating(arr, n);
}
}
|
Python3
def printRepeating(arr):
repeating_set = set ()
for i in range ( len (arr)):
repeating = False
for j in range (i + 1 , len (arr)):
if arr[i] = = arr[j]:
if not repeating:
repeating_set.add(arr[i])
repeating = True
break
for item in repeating_set:
print (item, end = " " )
if __name__ = = "__main__" :
arr = [ 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 ]
printRepeating(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void Main()
{
int [] arr = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = arr.Length;
PrintRepeating(arr, n);
}
static void PrintRepeating( int [] arr, int n)
{
HashSet< int > set = new HashSet< int >();
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) {
set .Add(arr[i]);
}
repeating = true ;
break ;
}
}
}
foreach ( int item in set )
{
Console.Write(item + " " );
}
}
}
|
Javascript
function printRepeating(arr) {
const s = new Set();
const n = arr.length;
for (let i = 0; i < n; i++) {
let repeating = false ;
for (let j = i + 1; j < n; j++) {
if (arr[i] === arr[j]) {
if (!repeating) {
s.add(arr[i]);
}
repeating = true ;
break ;
}
}
}
for (const item of s) {
console.log(item);
}
}
const arr = [12, 10, 9, 45, 2, 10, 10, 45];
printRepeating(arr);
|
Time Complexity: O(n^2) .
Auxiliary Space: O(k), where k is the number of repeating element .
Array elements that appear more than once using 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printRepeating( int arr[], int n)
{
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++)
mp[arr[i]]++;
for ( int i = 0; i < n; i++) {
if (mp[arr[i]] > 1) {
cout << arr[i] << " " ;
mp[arr[i]] = 0;
}
}
}
int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof (arr) / sizeof (arr[0]);
printRepeating(arr, n);
return 0;
}
|
Java
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.lang.*;
public class GFG {
static void printRepeating( int arr[], int n)
{
Map<Integer, Integer> map
= new LinkedHashMap<Integer, Integer>();
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 );
}
}
for (Entry<Integer, Integer> e : map.entrySet()) {
if (e.getValue() > 1 ) {
System.out.print(e.getKey() + " " );
}
}
}
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);
}
}
|
Python3
def printRepeating(arr, n):
mp = [ 0 ] * 100
for i in range ( 0 , n):
mp[arr[i]] + = 1
for i in range ( 0 , n):
if (mp[arr[i]] > 1 ):
print (arr[i], end = " " )
mp[arr[i]] = 0
arr = [ 12 , 10 , 9 , 45 ,
2 , 10 , 10 , 45 ]
n = len (arr)
printRepeating(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void printRepeating( int []arr, int n)
{
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);
}
}
foreach (KeyValuePair< int , int > e in map)
{
if (e.Value > 1)
{
Console.Write(e.Key + " " );
}
}
}
public static void Main(String[] args)
{
int []arr = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = arr.Length;
printRepeating(arr, n);
}
}
|
Javascript
function printRepeating(arr, n)
{
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)
}
for ( var i = 0; i < n; i++) {
if (mp.get(arr[i]) > 1) {
console.log( arr[i] + " " );
mp.set(arr[i], 0);
}
}
}
var arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];
var n = arr.length;
printRepeating(arr, n);
|
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.
Array elements that appear more than once 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++
#include <iostream>
#include <unordered_map>
using namespace std;
void printRepeating( int arr[], int n)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
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[0]);
printRepeating(arr, n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void printRepeating( int [] arr, int n)
{
Map<Integer, Integer> freq
= new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++) {
int key = arr[i];
freq.put(key, freq.getOrDefault(key, 0 ) + 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
from collections import Counter
def printRepeating(arr, n):
freq = Counter(arr)
for i in freq:
if (freq[i] > 1 ):
print (i, end = " " )
arr = [ 12 , 10 , 9 , 45 ,
2 , 10 , 10 , 45 ]
n = len (arr)
printRepeating(arr, n)
|
C#
using System;
using System.Collections.Generic;
public class Program {
public static void printRepeating( int [] arr, int n)
{
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;
}
}
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 printRepeating(arr, n) {
let freq = {};
for (let i = 0; i < n; i++) {
if (freq[arr[i]] === undefined) {
freq[arr[i]] = 1;
} else {
freq[arr[i]]++;
}
}
for (let key in freq) {
if (freq[key] > 1) {
console.log(key);
}
}
}
let arr = [12, 10, 9, 45,
2, 10, 10, 45];
let n = arr.length;
printRepeating(arr, n);
|
Time complexity: O(n), where n is the number of elements in the input array arr.
Auxiliary Space: O(n), where n represents the size of the given array.
Array elements that appear more than once using Binary Search:
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++
#include <bits/stdc++.h>
using namespace std;
void printRepeating( int arr[], int n)
{ sort(arr,arr+n);
for ( int i=0;i <n ;i++)
{
int first_index = lower_bound(arr,arr+n,arr[i])- arr;
int last_index = upper_bound(arr,arr+n,arr[i])- arr-1;
int fre = last_index-first_index+1;
if (fre > 1 )
{ i=last_index;
cout<<arr[i]<< " " ; }
}
}
int main()
{
int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = sizeof (arr) / sizeof (arr[0]);
printRepeating(arr, n);
return 0;
}
|
Java
import java.util.*;
class Main {
public static void printRepeating( int arr[], int n)
{
Arrays.sort(arr);
for ( int i = 0 ; i < n; i++) {
int first_index = Arrays.binarySearch(arr, arr[i]);
int last_index = Arrays.binarySearch(arr, arr[i]);
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 ;
if (fre > 1 )
{
i = last_index;
System.out.print(arr[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
def printRepeating(arr, n):
arr.sort()
i = 0
while i < n:
first_index = i
last_index = i + arr.count(arr[i]) - 1
if last_index - first_index > 0 :
print (arr[i], end = " " )
i = last_index + 1
arr = [ 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 ]
n = len (arr)
printRepeating(arr, n)
|
C#
using System;
using System.Linq;
class GFG {
static void printRepeating( int [] arr, int n)
{
Array.Sort(arr);
for ( int i = 0; i < n; i++) {
int first_index
= Array.BinarySearch(arr, arr[i]);
int last_index = Array.LastIndexOf(arr, arr[i]);
int fre = last_index - first_index + 1;
if (fre > 1) {
i = last_index;
Console.Write(arr[i] + " " );
}
}
}
static void Main()
{
int [] arr = { 12, 10, 9, 45, 2, 10, 10, 45 };
int n = arr.Length;
printRepeating(arr, n);
}
}
|
Javascript
function printRepeating(arr, n) {
arr.sort();
let i = 0;
while (i < n) {
let first_index = i;
let last_index = i + arr.filter(x => x === arr[i]).length - 1;
if (last_index - first_index > 0) {
console.log(arr[i]);
}
i = last_index + 1;
}
}
let arr = [12, 10, 9, 45, 2, 10, 10, 45];
let n = arr.length;
printRepeating(arr, n);
|
Time Complexity: O(n*log2n), Take log2n for binary search function(upper and lower bound)
Auxiliary Space: O(1)
Last Updated :
30 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...