[Solved] 2 Ways To Find Duplicate Elements In A Given Array In Java

Pages

  • Home
  • core java
  • spring
  • online courses
  • thread
  • java 8
  • coding
  • sql
  • books
  • oop
  • interview
  • certification
  • free resources
  • best
[Solved] 2 Ways to Find Duplicate Elements in a given Array in Java - Example Hello guys, today, you will learn how to solve another popular coding problem. You have given an array of objects, which could be an array of integers and or an array of Strings or any object which implements the Comparable interface. How would you find duplicate elements from an array? Can you solve this problem in O(n) complexity? This is actually one of the frequently asked coding questions from Java interviews. There are multiple ways to solve this problem, and you will learn two popular ways here, first the brute force way, which involves comparing each element with every other element, and other which uses a hash table-like data structure to reduce the time complexity of the problem from quadratic to linear, of course by trading off some space complexity. This also shows how by using a suitable data structure, you can come up with a better algorithm to solve a problem. That's why a good knowledge of Data Structure and Algorithms are very important for all programmers. If you are new to the programming world or want to refresh your knowledge about essential data structures like an array, string, linked list, hash table, binary tree, balanced tree, stack, queue, priority queue, etc then I suggest you go through a comprehensive data structure and algorithms course. According to Data Structures and Algorithms: Deep Dive Using Java course learning all essential data structures and algorithms like searching, sorting, and graph-based algorithms can make you better developer and also help in cracking coding interviews.

How to find duplicates in a given array on O(n^2)

In the first solution, we compare each element of the array to every other element. If it matches then its duplicate and if it doesn't, then there are no duplicates. This is also known as a brute force algorithm to find duplicate objects from Java array. The time complexity of this problem is O(n^2) or quadratic. When you give this solution to your interviewer, he will surely ask you to come up with O(n) time complexity algorithm, which we will see next. Here is the code to find duplicate elements using a brute force algorithm in Java: In this program, instead of printing the duplicate elements, we have stored them in a Set and returned from the method, but if the interviewer doesn't ask you to return duplicates, then you can simply print them into the console as I have done in next solution. public static Set<Integer> findDuplicates(int[] input) { Set<Integer> duplicates = new HashSet<Integer>(); for (int i = 0; i < input.length; i++) { for (int j = 1; j < input.length; j++) { if (input[i] == input[j] && i != j) { // duplicate element found duplicates.add(input[i]); break; } } } return duplicates; } If you are preparing for programming job interviews, then I also suggest you take a look at the Grokking the Coding Interview: Patterns for Coding Questions course on Educative, which contains many popular patterns for solving coding problems. This means you don't need to solve 100+ Leedcode problems but just need to learn a few patterns which are applicable to many programming problems. How to find duplicate elements in an Array - Java

How to Find duplicates in array in O(n) time Complexity

The second solution demonstrates how you can use a suitable data structure to come up with a better algorithm to solve the same problem. If you know, in Java, the Set interface doesn't allow duplicates, and it's based upon hash table data structure, so insertion takes O(1) time in the average case. By using HashSet, a general-purpose Set implementation, we can find duplicates in O(n) time. All you need to do is iterate over an array using advanced for loop and insert every element into HashSet. Since it allows only unique elements, add() method will fail and return false when you try to add duplicates. Bingo, you have to find the duplicate element, just print them off to console, as shown in the following program: public static <T extends Comparable<T>> void getDuplicates(T[] array) { Set<T> dupes = new HashSet<T>(); for (T i : array) { if (!dupes.add(i)) { System.out.println("Duplicate element in array is : " + i); } } } This solution also demonstrates how you can use Generics to write type-safe code in Java. This method will work on any type of Java array, like Array with Integer, Array with String or any object which implements Comparable interface, but will not work with a primitive array because they are not objects in Java. If you are preparing for programming job interviews, then I also suggest you take a look at the Cracking the Coding Interview book by Gayle McDowell, which contains 189 programming questions and solutions, good enough to do well on any programming job interviews like Java, C++, Python or Ruby. How to find duplicate elements in Java array coding

Java Program to find duplicate elements in Java using Generics

Here is the Java program to combine both solutions, you can try running this solution on Eclipse IDE and see how it works. You can also write the JUnit test to see our solution work in all cases, especially corner cases like an empty array, array with null, etc. import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static java.lang.System.*; /** * Java Program to find duplicate elements in an array. In this program, you * will learn two solution to find duplicate elements in integer array e.g. * brute force, by using HashSet data structure. * * @author java67 */ public class DuplicatesFromArray{ public static void main(String args[]) { int[] withDuplicates = { 1, 2, 3, 1, 2, 3, 4, 5, 3, 6 }; Set<Integer> duplicates = findDuplicates(withDuplicates); out.println("input array is : " + Arrays.toString(withDuplicates)); out.println("Duplicate elements found in array are : " + duplicates); // now calling our generic method to find duplicates String[] myArray = { "ab", "cd", "ab", "de", "cd" }; out.println("input string array is : " + Arrays.toString(myArray)); getDuplicates(myArray); } /** * Complexity of this solution is O(n^2) * * @param input * @return */ public static Set<Integer> findDuplicates(int[] input) { Set<Integer> duplicates = new HashSet<Integer>(); for (int i = 0; i < input.length; i++) { for (int j = 1; j < input.length; j++) { if (input[i] == input[j] && i != j) { // duplicate element found duplicates.add(input[i]); break; } } } return duplicates; } /** * Generic method to find duplicates in array. Complexity of this method is * O(n) because we are using HashSet data structure. * * @param array * @return */ public static <T extends Comparable<T>> void getDuplicates(T[] array) { Set<T> dupes = new HashSet<T>(); for (T i : array) { if (!dupes.add(i)) { System.out.println("Duplicate element in array is : " + i); } } } } Output : input array is : [1, 2, 3, 1, 2, 3, 4, 5, 3, 6] Duplicate elements found in array are : [1, 2, 3] input string array is : [ab, cd, ab, de, cd] Duplicate element in array is : ab Duplicate element in array is : cd That's all about how to find duplicate elements in an array. You have now learned two ways to solve this problem in Java. The first solution is the brute force algorithm, which is demonstrated by finding duplicate elements on integer array, but you can use the logic to find a duplicate on any kind of array. The second solution uses the HashSet data structure to reduce the time complexity from O(n^2) to O(n), and it also shows you can write generic methods to find duplicates on any object array.

Other Coding Problems for Practice

  • How to print the Pyramid pattern in Java? (solution)
  • 10 Free Courses to learn Data Structure and Algorithms (courses)
  • How to check if a given number is prime or not? (solution)
  • How to solve the FizzBuzz problem in Java? (solution)
  • 7 Best Courses to learn Data Structure and Algorithms (best courses)
  • 100+ Data Structure and Algorithms Problems (solved)
  • 10 Books to learn Data Structure and Algorithms (books)
  • Write a program to print the highest frequency word from a text file? (solution)
  • How to remove duplicate elements from ArrayList in Java? (solution)
  • How to find if given String is a palindrome in Java? (solution)
  • How to find a missing number in a sorted array? (solution)
  • How to calculate factorial using recursion and iteration? (solution)
  • How do you reverse word of a sentence in Java? (solution)
  • How to find duplicate characters from String in Java? (solution)
  • How to reverse an int variable in Java? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • Write code to implement the Bubble sort algorithm in Java? (code)
  • Top 10 Programming problems from Java Interviews? (article)
  • Write code to implement the Quicksort algorithm in Java? (algorithm)
  • How do you swap two integers without using a temporary variable? (solution)
  • Write a program to check if a number is the power of two or not? (solution)
  • How to reverse String in Java without using StringBuffer? (solution)
  • Write a program to code insertion sort algorithm in Java (program)
Thanks for reading this article so far. If you like this array-based coding Interview question, then please share it with your friends and colleagues. If you have any doubts or feedback, then please drop a note. P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free, and all you need to do is create a free Udemy account to enroll in this course.

3 comments:

  1. AnonymousNovember 25, 2018 at 7:57 AM

    How about checking the array for duplicates in string and convert the duplicates to uppercase??The should be inputted by a user not given.

    ReplyDeleteReplies
      Reply
  2. javin paulMay 11, 2022 at 7:42 AM

    This question was asked to me on Java developer interview, thanks

    ReplyDeleteReplies
    1. AnonymousJanuary 25, 2024 at 9:22 AM

      4 years later is crazy lmao

      DeleteReplies
        Reply
    2. Reply
Add commentLoad more...

Feel free to comment, ask questions if you have any doubt.

Newer Post Older Post Home Subscribe to: Post Comments (Atom)

Recommended Courses

  • best python courses
  • best java courses
  • system design courses
  • best spring courses
  • best hibernate courses
  • best design pattern courses
  • best Linux courses
  • best JavaScript courses
  • best data structure and algorithms courses
  • Best Multithreading Courses
  • best MERN stack courses
  • Best Git courses
  • Best Microservice Courses
  • Best DevOps Courses
  • best MEAN stack Courses
  • free Java courses
  • free DSA courses
  • free sql courses
  • free Linux courses
  • Free Docker courses
  • free JUnit courses

Array Tutorials

  • array - copy
  • array - tutorial
  • array - add/remove element
  • array - linked list
  • array - reverse
  • array - sorting
  • array - sum
  • array - binary search
  • array - vector
  • array - remove
  • array - reverse in place
  • array - to list
  • array - initialization
  • array - insertion sort
  • array - to string
  • array - example
  • array - data structure
  • array - compare
  • array - liner search

Categories

  • .NET
  • abstract class
  • ActiveMQ
  • Affiliate marketing
  • After Effects
  • Agentic AI
  • Agile
  • AI Tools
  • Amazon Web Service
  • android
  • Angular
  • Anonymous class
  • Ansible
  • apache camel
  • Apache kafka
  • Apache spark
  • app development
  • array
  • ArrayList
  • Artificial Intelligence
  • automation
  • aws
  • aws certification
  • Azure Certifications
  • backend development
  • bash
  • basics
  • beginners
  • best of java67
  • best practices
  • Big Data
  • binary tree
  • bit manipulation
  • black friday deals
  • Blockchain
  • BlockingDeque
  • books
  • Bootstrap
  • business analysis
  • ByteByteGo
  • C programming
  • C++
  • Career
  • ChatGPT
  • Chef
  • cloud certification
  • Cloud Computing
  • Code Example
  • Code Review
  • codecademy
  • Codemia
  • CodeRabbit
  • coding
  • coding exercise
  • Coding Interview
  • Coding Problems
  • Comparator
  • computer science
  • Computer Vision
  • concurrency tutorial
  • ConcurrentHashMap
  • core java
  • core java interview question answer
  • course review
  • Coursera
  • courses
  • crontab
  • CSS
  • Cyber Monday
  • Cyber Security
  • Data Analysis
  • data science
  • data structure and algorithm
  • Data Visualization
  • database
  • datacamp
  • date and time
  • debugging
  • deep learning
  • default methods
  • design pattern
  • DevOps
  • DevSecOps
  • Distributed Systems
  • Django
  • docker
  • double
  • Drawing
  • DSA
  • dyanmic programming
  • dynamic Programming
  • eBooks
  • Eclipse
  • EJB
  • enum
  • equals
  • error and exception
  • Ethical hacking
  • Excel
  • exception
  • Exponent
  • expressjs
  • FAANG
  • Figma
  • Firebase
  • flatmap
  • float
  • Flutter
  • free resources
  • freelancing
  • Frontend Masters
  • fun
  • Fundamental
  • fundamentals
  • Game development
  • garbage collection
  • general
  • Generics
  • gifts
  • git and github
  • golang
  • Google Cloud Certification
  • Google Cloud Platform
  • Gradle
  • grails
  • graph
  • graphic design
  • grep
  • Groovy
  • gRPC
  • Hadoop
  • HashMap
  • HashSet
  • haskell
  • Hibernate
  • Hibernate interview Question
  • homework
  • HTML
  • HTTP
  • HttpClient
  • i
  • interface
  • Internet of Things (IoT)
  • interview
  • interview questions
  • IT Certification
  • J2EE
  • Jackson
  • java
  • Java 5 tutorial
  • java 7
  • Java 8
  • java 9
  • java basics
  • Java Certification
  • Java collection tutorial
  • java concurrency tutorial
  • java design pattern
  • Java Enum
  • Java file tutorials
  • Java Functional Programming
  • Java Installation Guide
  • Java Interview Question
  • Java interview questions
  • Java IO interview question
  • java io tutorial
  • java map tutorials
  • java modules
  • Java Multithreading Tutorial
  • Java networking tutorial
  • Java Operator tutorial
  • Java programming Tutorial
  • Java String tutorial
  • Java7
  • JavaScript
  • JavaScript Interview Question
  • JavaScript Tutorial
  • JDBC
  • JEE Interview Questions
  • Jenkins
  • JMS
  • JPA
  • jQuery
  • JSON
  • JSP
  • JSP Interview Question
  • JSTL
  • JUnit
  • JVM
  • Keras
  • keystore
  • Kotlin
  • kubernetes
  • lambda expression
  • Laraval
  • learning
  • linked list
  • Linux
  • Log4j
  • logging
  • Lombok
  • LSAT
  • Mac OS X
  • machine learning
  • Mathematics
  • Matlab
  • Maven
  • MERN stack
  • Messaging
  • Microservices
  • Microsoft
  • Microsoft Azure Platform
  • Microsoft Excel
  • Microsoft Power BI
  • Mockito
  • MongoDB
  • MysQL
  • MySQL tutorial example
  • nested class
  • neural network
  • Next.js
  • NFT
  • NLP
  • Node.js
  • nslookup
  • object oriented programming
  • OCAJP
  • OCMJEA
  • OCPJP
  • offers
  • Oracle
  • Perl
  • personal development
  • Photoshop
  • PHP
  • pluralsight
  • PostgerSQL
  • postman
  • Powerpoint
  • programmers
  • programming
  • programming problems
  • Project Management
  • projects
  • Prompt Engineering
  • Proxy
  • Python
  • Pytorch
  • Quarkus
  • questions
  • Queue
  • R programming
  • RabbitMQ
  • React
  • React Hooks
  • react native
  • Record
  • Recursion
  • Redux
  • regular expression example
  • REST tutorials
  • Review
  • RoadMap
  • Ruby
  • Salesforce
  • SAT
  • Scala
  • Scala Interview Questions
  • Scalability
  • Scanner
  • scripting
  • Scrum
  • Scrum Master Certification
  • Selenium
  • SEO
  • Serialization
  • Servlet
  • Servlet Interview Questions
  • Set
  • shell scripting
  • smart contracts
  • Snowflake SnowPro Certification
  • soft link
  • soft skills
  • software architecture
  • Solaris
  • Solidity
  • Sorting Algorithm
  • Spark
  • spring boot
  • Spring Certification
  • spring cloud
  • spring data jpa
  • spring framework
  • spring interview question
  • spring mvc
  • spring security
  • sql
  • SQL interview Question
  • SQL Joins
  • SQL SERVER
  • ssl
  • Static
  • Statistics
  • Stream
  • String
  • Struts
  • Swift
  • swing
  • switch case
  • system design
  • System Design Interview Questions
  • Tableau
  • Tailwind
  • TensorFlow
  • ternary operator
  • testing
  • thread
  • thread interview questions
  • Time series analysis
  • Tips
  • tomcat
  • tools
  • tree
  • TreeMap
  • troubleshooting
  • TypeScript
  • Udacity
  • Udemy
  • UI and UX Design
  • UML
  • unit testing
  • Unity 3D
  • Unix
  • unreal engine
  • Video Editing
  • Vuejs
  • web design
  • web development
  • web scrapping
  • Web Service
  • Whizlabs
  • Wix
  • xml
  • YAML
  • ZTM Academy

Best System Design and Coding Interview Resources

System Design & Interview Prep

  • ByteByteGo Lifetime Plan (50% OFF)
  • Codemia Lifetime Plan (60% OFF)
  • Exponent Annual Plan (70% OFF)
  • Educative Premium Plus (55% OFF)
  • DesignGurus All Course Bundle (55% OFF)
  • Everything Java Interview Bundle (50% OFF)
  • 101 Blockchain (50% OFF)
  • Vlad Mihalcea's High Performance Bundle (50% OFF)
  • Javarevisited Substack Subscription (50% OFF)
  • Head First Software Architecture (Book)

Search This Blog

Best Online Learning Resources and Platforms

  • Coursera Plus (40% OFF)
  • Datacamp Sale (50% OFF)
  • AlgoMonster Lifetime Plan (50% OFF)
  • Udemy Sale (80% OFF)
  • Baeldung (33% OFF)
  • LabEx Sale (50% OFF)
  • Codecademy Sale (60% OFF)
  • Udacity Sale (50% OFF)
  • ZTM Academy Sale (66% OFF)
  • Frontend Masters Deal
  • Whizlabs Deal (70% OFF)

Javarevisited

Loading...

Spring Interview Prep List

  • Spring Boot Interview questions
  • Spring Cloud Interview questions
  • Spring MVC Interview Questions
  • Microservices Interview questions
  • 10 Spring MVC annotations
  • Spring Boot Courses
  • Spring Framework Courses

Subscribe for Discounts and Updates

Follow

Interview Questions

  • core java interview questions
  • SQL interview questions
  • data structure interview question
  • coding interview questions
  • java collection interview questions
  • java design pattern interview questions
  • thread interview questions
  • hibernate interview questions
  • j2ee interview questions
  • Spring Interview Questions
  • object oriented programming questions

Followers

Blog Archive

  • ▼  2025 (554)
    • ▼  June (103)
      • JDBC - How to get Row and Column Count From Result...
      • Can You Create Instance of Abstract class in Java?...
      • How to convert String to Enum in Java? ValueOf Exa...
      • The Ultimate Guide to Package in Java? Examples
      • How to read a file line by line in Java? BufferedR...
      • Java Enum with Constructor Example
      • Could not create the Java virtual machine Invalid ...
      • ArrayList vs Vector in Java? Interview Question An...
      • The Ultimate Guide of Enum in Java - Examples
      • What is class file in Java? Example
      • Difference between static and non static nested cl...
      • How to read file in Java using Scanner Example - t...
      • Difference between throw vs throws in Java? Answer
      • How to read User Input from Console in Java? Scann...
      • How to Find IP address of localhost or a Server in...
      • 15 People Java Developers Should Follow on Twitter
      • Java Keyword Cheat Sheet - Meaning and Usage
      • Video example - Dijkstra's Algorithm shortest path...
      • How to remove duplicate(s) from linked list in Jav...
      • How to find Factorial in Java using Recursion and ...
      • How to calculate perimeter and area of square in J...
      • How to solve word break problem in Java using dyna...
      • How to calculate Compound Interest in Java? Compou...
      • How to check if a Number is Power of Two in Java? ...
      • [Solved] How to count Vowels and Consonants in Jav...
      • [Solved] How to convert Hexadecimal to Decimal, Bi...
      • How to create a Function to add two numbers in Jav...
      • [Solved] How to solve climbing stairs problem in J...
      • How to Search an Element in Java Array with Exampl...
      • [Solved] How to solve a coin change problem in Jav...
      • How to print a Right Triangle Pattern in Java - Ex...
      • [Solved] How to convert Decimal to Binary Number i...
      • [Solved] How to find all pairs which add up to a g...
      • 2 Ways to solve FizzBuzz in Java? [Example]
      • How to Find Highest Repeating Word from a File in ...
      • How to Check if Given Number is Prime in Java - Wi...
      • [Solved] How to Find 2 Largest Number from Integer...
      • [Solved] How to Check If a Given String has No Dup...
      • How to Find Greatest Common Divisor of two numbers...
      • How to calculate sum of all numbers in a given arr...
      • [Solved] 2 Ways to Find Duplicate Elements in a gi...
      • [Solved] How to reverse a String in place in Java?...
      • Top 10 Algorithms books Every Programmer Should Read
      • How to implement Level Order Traversal of Binary T...
      • How to Implement Binary Tree InOrder traversal in ...
      • How to remove duplicate characters from String in ...
      • How to find median of two sorted arrays in Java? E...
      • Fibonacci Series in Java Using Recursion
      • How to Reverse an Integer in Java without converti...
      • How to Find Nth Fibonacci Number in Java [Solved] ...
      • How to implement Linear Search Algorithm in Java? ...
      • How to implement Radix Sort in Java - Algorithm Ex...
      • How to implement Merge Sort Algorithm in Java [So...
      • Counting Sort in Java - Example
      • Top 22 Array Concepts Interview Questions Answers ...
      • How to use Deque Data Structure in Java? Example T...
      • How to find Kth Smallest Element in a Binary Searc...
      • How to find the maximum sum level in binary tree i...
      • How to Find Lowest Common Ancestor of a Binary Tre...
      • How to get the first and last item in an array in ...
      • Difference between array and Hashtable or HashMap ...
      • [Solved] How to find the Longest common prefix in ...
      • How to check if a node exists in a binary tree or...
      • How to use Recursion in JavaScript? Example Tutorial
      • How to find 2nd, 3rd or kth element from end in li...
      • 10 Examples of an Array in Java
      • How to Print all leaf Nodes of a Binary tree in Ja...
      • 10 Examples of Array Data Structure in Java
      • Top 40 Binary Tree Coding Interview Questions for ...
      • Top 25 Linked List Coding Interview Questions for ...
      • [Solved] How to check if two String are Anagram in...
      • How to create a String or int Array in Java? Examp...
      • How to Find/Print Leaf nodes in a Binary Tree in J...
      • How to check If two Strings Array are equal in Jav...
      • Top 5 Free Servlet, JSP, Java FX, and JDBC Course...
      • Top 6 Dynamic Programming Online Courses for Codin...
      • 5 Free Online Courses to Learn Kotlin in 2025 - Be...
      • Top 6 Free Courses to Learn Bootstrap Online for B...
      • Difference between Binary Tree, Binary Search Tre...
      • [Solved] How to Find Repeated Characters in a give...
      • How to solve Two Sum Array Problem in Java? Example
      • 6 Essential Data Structures Java Programmer should...
      • Post order traversal Algorithms for Binary Tree in...
      • How to check if an array includes a value in JavaS...
      • How to sort an Array in descending order in Java? ...
      • QuickSort Algorithm Example in Java using Recursio...
      • How to remove a number from an Integer Array in Ja...
      • How Binary Search Algorithm Works? Java Example wi...
      • How to declare and Initialize two dimensional Arra...
      • How to compare two Arrays in Java to check if they...
      • How to Convert or Print Array to String in Java? E...
      • How to implement PreOrder traversal of Binary Tree...
      • How to reverse a singly linked list in Java withou...
      • How to Reverse an Array in place in Java? Example ...
      • 5 Differences between an array and linked list in ...
      • How to code Binary Search Algorithm using Recursio...
      • Post Order Binary Tree Traversal in Java Without R...
      • 7 Examples to Sort One and Two Dimensional String ...
      • Insertion Sort Algorithm in Java with Example
      • How to Rotate an Array to Left or Right in Java? S...

Privacy

  • Privacy Policy
  • Terms & Conditions

Popular Posts

  • 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
  • How to fix "illegal start of expression" error in Java? Example
  • 5 Examples of Formatting Float or Double Numbers to String in Java
  • Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
  • Top 10 Frequently asked SQL Query Interview Questions Answers

Subscribe

Get new posts by email:
Subscribe

Tag » How To Find Duplicate Number In Array Java