HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Puzzles / Java puzzle – Find all the duplicate elements

Java puzzle – Find all the duplicate elements

Puzzle: Given an input array of n positive integers where the integers are in random order. Each number in that array can occur many times. You need to find all the distinct elements and put all those elements in an array i.e. output1. If no number is duplicated in input, then output should be {-1}.

Input Specifications: input: number of elements in input2 (n) input 2: an array of n positive integers

Output Specifications: output: an array of distinct elements which are duplicate in input2

Example 1: input : 6 input2 : {4,4,7,8,8,9} output : {4,8} 
Example 2: input : {2,3,6,8,90,58,58,60} output : {58} 
Example 3: input : {3,6,5,7,8,19,32} output : {-1}

Solution

import java.util.HashSet;
import java.util.Set;
 
public class DuplicatesInArray
{
    public static void main(String[] args)
    {
        Integer[] array = {1,2,3,4,5,6,7,8};  //input 1
        int size = array.length;              //input 2
         
        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> duplicates = new HashSet<Integer>();
          
        for(int i = 0; i < size ; i++)
        {
            if(set.add(array[i]) == false)
            {
                duplicates.add(array[i]);
            }
        }
         
        if(duplicates.size() == 0)
        {
            duplicates.add(-1);
        }
         
        System.out.println(duplicates);
    }
}

The above program will find all duplicate elements from the array and put them into a separate set. You can find more discussion on this logic here: //howtodoinjava.com/java/interviews-questions/find-duplicate-elements-in-an-array/

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Vassilis

    April 7, 2020

    List input = Arrays.asList(1, 2, 5, 2, 5, 5, 1, 6, 9);
    
    Map frequencies = input.stream()
         .collect(Collectors.groupingBy(n -&gt; n, Collectors.counting()));
    
    frequencies.entrySet().stream()
        .filter(entry -&gt; entry.getValue() &gt; 1)
        .forEach(System.out::println);
  2. Juan David Gomez

    November 12, 2019

    A better approach with stream will be

            Set<Integer> uniques = new HashSet<>();
            Set<Integer> collect = duplicates.stream()
                    .filter(integer -> !uniques.add(integer))
                    .collect(Collectors.toSet());
    

    or

            Set<Integer> collect  = duplicates.stream()
                    .filter(integer -> Collections.frequency(duplicates, integer) > 1)
                    .collect(Collectors.toSet());
    
Comments are closed on this article!

Search Tutorials

Java Puzzles

  • Interview Puzzles List
  • Dead vs Unreachable Code
  • Palindrome Number
  • Detect infinite loop in LinkedList
  • [i += j] Vs [i = i + j]
  • HiLo Guessing Game
  • Find All Distinct Duplicate Elements
  • TreeMap Put Operation
  • String With Nth Longest Length
  • Good String Vs Bad String
  • Complete String
  • Reverse String
  • Calculate Factorial
  • FizzBuzz Solution
  • Find Missing Number From Series
  • Create Instance Without New Keyword

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces