Java program for finding repeating element in an array

Repeating element of an array in Java

In this section, we will learn the Program to Find Repeating element of an array in java.Given an array, print all element whose frequency is not equal to one. We will discuss different approaches to print the repeated elements of given input array.

Repeating elements in an array in java

Methods Discussed are :

  • Method 1 : Using Two loops
  • Method 2 : Using hash Map.
  • Method 3 : Using Sorting

Now, let’s discuss the algorithm for both methods.

Method 1 :

In this method we will count the frequency of each elements using two for loops.

  • To check the status of visited elements create a array of size n.
  • Run a loop from index 0 to n and check if (visited[i]==1) then skip that element.
  • Otherwise create a variable count = 1 to keep the count of frequency.
  • Run a loop from index i+1 to n
  • Check if(arr[i]==arr[j]), then increment the count by 1 and set visited[j]=1.
  • After complete iteration of inner for loop and print the element if(count!=1)

Time and Space Complexity :

  • Time Complexity : O(n2)
  • Space Complexity : O(n)

Method 1 : Code in Java

Run
import java.util.Arrays;

class Main
{
   public static void countFreq(int arr[], int n)
   {
         boolean visited[] = new boolean[n];
         Arrays.fill(visited, false);
     
         // Traverse through array elements and
         // count frequencies
         for (int i = 0; i < n; i++) {

            // Skip this element if already processed
            if (visited[i] == true)
             continue;

            // Count frequency
            int count = 1;
            for (int j = i + 1; j < n; j++) {
                if (arr[i] == arr[j]) {
                   visited[j] = true;
                   count++;
                }
            }
            if(count!=1)   
               System.out.println(arr[i]);
   }
} // Driver code 

public static void main(String []args) 
{ 
int arr[] = new int[]{10, 30, 30, 20, 10, 20, 50, 10};
 int n = arr.length; 
countFreq(arr, n); 
} 
}

Output

10
30
20

Method 2 :

In this method we will count use hash-map to count the frequency of each elements.

  • Declare a hash map
  • Start iterating over the entire array
  • If element is present in map, then increase the value of frequency by 1.
  • Otherwise, insert that element in map.
  • After complete iteration over array, start traversing map and if(value==1) then print that element.

Time and Space Complexity :

  • Time Complexity : O(n)
  • Space Complexity : O(n)
Repeated element in Java

Method 2 : Code in Java

Run
import java.util.*;
import java.util.Arrays;

class Main
{
static void countFreq(int arr[], int n)
{
Map<Integer, Integer> mp = new HashMap<>();

// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
{
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
}
// Traverse through map and print frequencies
for (Map.Entry<Integer, Integer> entry : mp.entrySet())
{ if(entry.getValue()>1)
System.out.println(entry.getKey()+" ");
}

}
// Driver code
public static void main(String []args)
{
int arr[] = new int[]{10, 30, 50, 20, 10, 20, 30, 10};
int n = arr.length;
countFreq(arr, n);
}
}

Output

20 
10 
30 

Method 3 :

In this method it is necessary that the array is sorted. So we will use bubble sort to sort the given array. 

Method 3 : code in Java

Run
import java.util.*;
import java.util.Arrays;

class Main
{
   static int bubbleSort(int arr[], int size){
        for (int i = 0; i < size-1; i++){
            // Since, after each iteration righmost i elements are sorted 
              for (int j = 0; j < size-i-1; j++) if (arr[j] > arr[j+1]) 
              {
                    int temp = arr[j]; // swap the element
                    arr[j] = arr[j+1]; 
                    arr[j+1] = temp; 
              }
         } 
        return 0;
   } 

   static void findRepeating(int arr[], int n){
 
        int count = 0;
        for (int i = 0; i < n; i++) {

             int flag = 0;
             while (i < n - 1 && arr[i] == arr[i + 1]){
               flag = 1;
               i++;
             }
             // since i++ happened, we need to print previous element
             if(flag==1)
               System.out.print(arr[i-1] + " ");
        }
        return;
   }

   // Driver code
   public static void main(String []args)
   {
       int arr[] = new int[]{10, 30, 50, 20, 10, 20, 30, 10};
       int n = arr.length;
       bubbleSort(arr, n);
       findRepeating(arr, n);
   }
}

Output

10 20 30

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

11 comments on “Java program for finding repeating element in an array”


  • Gyanendra

    // Using HashMap
    import java.util.*;
    public class Main{
    public static void main(String[] args){
    Scanner scn=new Scanner(System.in);
    int n=scn.nextInt();
    int[] arr=new int[n];

    for(int i=0;i<n;i++){
    arr[i]=scn.nextInt();
    }

    Map map=new HashMap();
    int count=1;

    for(int i=0;i<arr.length;i++){
    int x=arr[i];

    if(x!=-1){

    for(int j=i+1;j<arr.length;j++){
    if(arr[i]==arr[j]){
    count++;
    arr[j]=-1;
    }
    }

    map.put(arr[i],count);

    count=1;
    }
    }
    for(Map.Entry mp: map.entrySet()){
    if(mp.getValue()>1){
    System.out.println(mp.getKey());
    }
    }

    }
    }


  • Gyanendra

    import java.util.*;
    public class Main{
    public static void main(String[] args){
    Scanner scn=new Scanner(System.in);
    int n=scn.nextInt();
    int[] arr=new int[n];

    for(int i=0;i<n;i++){
    arr[i]=scn.nextInt();
    }
    Arrays.sort(arr);

    int count=1;

    for(int i=0;i1){
    System.out.print(arr[i]+” “);
    count=1;
    }
    }

    if(count>1){
    System.out.println(arr[n-1]);
    }

    }
    }


  • Shyam

    import java.util.Arrays;

    public class Find_repeating_element_Prepinsta {
    public static void repeating(int []arr,int n){
    boolean visited[]=new boolean[n];
    Arrays.fill(visited,false);
    for(int i=0;i<arr.length;i++) {
    if (visited[i] == true) {
    continue;
    }
    int count = 1;
    for (int j = i + 1; j < arr.length; j++) {
    if (arr[i] == arr[j]) {
    visited[j] = true;}
    count++;

    }
    if (count != 1) {
    System.out.print(arr[i]);
    }
    }
    }
    public static void main(String[] args) {
    int a[]={1,2,3,2,1,4,5,6,6,7};
    int n= a.length;
    repeating(a,n);
    }
    }


  • Subhajit

    public class RepeatingEle {

    public static void repeatElement(int arr[], int n) {
    for (int i = 0; i < n; i++) {
    int count = 0;
    for (int j = i + 1; j 0) {
    System.out.print(arr[i] + ” “);
    }
    }
    System.out.println();
    }

    public static void main(String[] args) {
    int arr[] = { 10, 30, 40, 20, 10, 30, 65, 74, 65, 20, 50, 10 };
    int n = arr.length;
    repeatElement(arr, n);
    }
    }


  • Leela

    package Practice2;
    import java.util.Scanner;
    public class Frequency {

    public static void main(String[] args)
    {
    int a[]=new int[200];
    Scanner sc=new Scanner(System.in);
    System.out.println(“enter the array size”);
    int n=sc.nextInt();
    System.out.println(“enter the array elements”);
    for(int i=0;i<n;i++)
    {

    a[i]=sc.nextInt();
    }
    System.out.println("given array elements are");
    for(int i=0;i<=n;i++)
    {
    System.out.println("a"+"["+i+"]"+"="+a[i]);

    }
    int count=0;
    for(int i=0;i<=n;i++)
    {
    for(int j=i+1;j0) {
    System.out.println(a[i] + “is a duplicate number “);
    }
    }
    }
    }
    System.out.println(“no.of Equal elements”);
    System.out.println(count);
    }

    }


  • Dhivya

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Scanner;

    public class repeating_elem {
    public static void main(String[] args) {
    HashMap hc= new HashMap();
    Scanner s = new Scanner(System.in);
    int a[]= new int[5];
    for(int i=0;i< a.length;i++){
    a[i]= s.nextInt();

    }
    for(int i=0;i< a.length;i++){
    if(hc.containsKey(a[i])){
    hc.put(a[i],hc.get(a[i])+1);
    }
    else{
    hc.put(a[i],1);
    }

    }
    for(Map.Entry e: hc.entrySet()){
    if(e.getValue() >=2){
    System.out.print(e.getKey()+” ,”);
    }
    }

    }
    }


  • 06_Animesh

    /* package codechef; // don’t place package name! */

    import java.util.*;
    import java.lang.*;
    import java.io.*;

    /* Name of the class has to be “Main” only if the class is public. */
    class Codechef
    {
    public static void main (String[] args) throws java.lang.Exception
    {
    // your code goes here
    try{
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] arr = new int[20];
    for(int i=0;i<n;i++){
    arr[i] = sc.nextInt();
    }
    HashMap map = new HashMap();
    for(int i=0;i 1){
    System.out.print(item.getKey() + ” “);
    }
    }
    }catch(Exception e){
    return;
    }
    }
    }


  • Mahesh

    int[]a={1,2,42,13,3,55,3,23,55,45,6,25,5,5,53,34,34,33,35};
    Arrays.sort(a);
    for(int i=0;i<a.length-1;i++){
    if(a[i]==a[i+1]){
    System.out.print(a[i]+" ");
    }
    }


  • remy.burie

    So Java 7… Please use Java 8…

    private static void findDuplicatesUsingJava8(int[] inputArray)
    {
    Set uniqueElements = new HashSet();

    Set duplicateElements = Arrays.stream(inputArray)
    .filter(i -> !uniqueElements.add(i))
    .boxed()
    .collect(Collectors.toSet());

    System.out.println(duplicateElements);
    }


  • Om Prakash

    Code in Java :
    import java.util.Scanner;
    public class Print_repeating_elements
    {
    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    System.out.print(“Enter length: “);
    int length = sc.nextInt();
    int arr[] = new int[length];
    for(int i=0; i<length; i++)
    arr[i] = sc.nextInt();
    sc.close();
    for(int i=0; i<length; i++)
    {
    for(int j=0; j arr[j])
    {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    }
    }
    }
    int i=0;
    System.out.println(“Repeating elements are:”);
    while(i<length)
    {
    int count = 0;
    for(int j=i; j 1)
    System.out.println(arr[i]);
    i = i+count;
    }
    }
    }


    • pravin

      If we give input as { 1 2 1 1 3 } , then ‘1’ is printed 3 times. Isn’t that wrong ?