2 Ways to uncovering duplicate elements inwards an Array - Java

Problem: You receive got given an array of objects, which could hold out an array of integers too or array of Strings or whatever object which implements the Comparable interface. How would you lot detect duplicate elements from an array? Can you lot solve this occupation inwards O(n) complexity? This is truly 1 of the often asked coding problems from Java interviews. There are multiple ways to solve this occupation too you lot volition acquire ii pop ways here, showtime the animate beingness forcefulness way, which involves comparison each chemical subdivision amongst every other chemical subdivision too other which uses a hash tabular array similar information construction to cut back the fourth dimension complexity of occupation from quadratic to linear, of class past times trading off about infinite complexity. This too shows that how past times using a suitable information construction you lot tin laissez passer on the axe come upward up amongst a amend algorithm to solve a problem. If you lot are preparing for programming labor interviews, thence I too advise you lot receive got a await at Cracking the Coding Interview book, which contains 150 programming questions too solutions, skilful plenty to produce good on whatever programming labor interviews e.g. Java, C++, Python or Ruby.


Logic of Solution 1 - finding duplicates inwards O(n^2)

In the showtime solution, nosotros compare each chemical subdivision of the array to every other element. If it matches thence its duplicate too if it doesn't thence at that topographic point are no duplicates. This is too known equally brute forcefulness algorithm to detect duplicate objects from Java array. The fourth dimension complexity of this occupation is O(n^2) or quadratic. When you lot laissez passer on this solution to your interviewer, he volition certainly inquire you lot to come upward up amongst O(n) fourth dimension complexity algorithm, which nosotros volition meet next.



Here is the code to find duplicate elements using animate beingness force algorithm inwards Java:

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 chemical subdivision found                     duplicates.add(input[i]);                     break;                 }             }         }          return duplicates;     }
Here instead of printing the duplicate elements, nosotros receive got stored them inwards a Set too returned from the method, but if Interviewer doesn't inquire you lot to provide duplicates thence you lot tin laissez passer on the axe but impress them into console equally I receive got done inwards side past times side solution.


Logic of Solution 2 - finding duplicates inwards O(n)

Second solution demonstrate how you lot tin laissez passer on the axe utilisation a suitable information construction to come upward up amongst amend algorithm to solve the same problem. If you lot know, inwards Java, the Set interface doesn't let duplicates too its based upon hash tabular array information construction thence insertion receive got O(1) fourth dimension inwards average case. By using HashSet, a full general utilisation Set implementation, nosotros tin laissez passer on the axe detect duplicates inwards O(n) time. All you lot demand to produce is iterate over array using advanced for loop too insert every chemical subdivision into HashSet. Since it allows solely unique elements, add() method volition neglect too provide simulated when you lot travail to add together duplicates. Bingo, you lot receive got detect the duplicate element, exactly impress them off to console, equally shown inwards next 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 chemical subdivision inwards array is : " + i);             }         }      }
This solution too demonstrate how you lot tin laissez passer on the axe use Generics to write type-safe code inwards Java. This method volition function on whatever type of Java array e.g. Array amongst Integer, Array amongst String or whatever object which implements Comparable interface, but volition non function amongst primitive array because they are non object inwards Java.

 which could hold out an array of integers too or array of Strings or whatever object which implement 2 Ways to detect duplicate elements inwards an Array - Java



Java Program to detect duplicate elements inwards Java using Generics
Here is the Java plan to combine both solution, you lot tin laissez passer on the axe travail running this solution on Eclipse IDE too meet how it works. You tin laissez passer on the axe too write JUnit exam to meet our solution function inwards all cases peculiarly corner cases similar empty array, array amongst goose egg etc.

import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static java.lang.System.*;  /**  * Java Program to detect duplicate elements inwards an array. In this program, you lot  * volition acquire ii solution to detect duplicate elements inwards integer array e.g.  * animate beingness force, past times using HashSet information 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 institute inwards array are : " + duplicates);          // straightaway calling our generic method to detect 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 chemical subdivision found                     duplicates.add(input[i]);                     break;                 }             }         }          return duplicates;     }      /**      * Generic method to detect duplicates inwards array. Complexity of this method is      * O(n) because nosotros are using HashSet information 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 chemical subdivision inwards array is : " + i);             }         }      }  }  Output : input array is : [1, 2, 3, 1, 2, 3, 4, 5, 3, 6] Duplicate elements institute inwards array are : [1, 2, 3] input string array is : [ab, cd, ab, de, cd] Duplicate chemical subdivision inwards array is : ab Duplicate chemical subdivision inwards array is : cd

That's all nearly how to detect duplicate elements inwards an array. You receive got straightaway learned ii ways to solve this occupation inwards Java. First solution is the animate beingness forcefulness algorithm which is demonstrate past times finding duplicate chemical subdivision on integer array, but you lot tin laissez passer on the axe utilisation the logic to detect duplicate on whatever sort of array. Second solution uses HashSet information construction to cut back the fourth dimension complexity from O(n^2) to O(n) too it too shows you lot tin laissez passer on the axe write generic methods to detect duplicates on whatever object array.


Other Coding Problems for Practice

  • How to impress Pyramid blueprint inwards Java? (solution)
  • How to depository fiscal establishment check if a given publish is prime number or not? (solution)
  • How to solve FizzBuzz occupation inwards Java? (solution)
  • Write a plan to impress highest frequency give-and-take from a text file? (solution)
  • How to take duplicate elements from ArrayList inwards Java? (solution)
  • How to detect if given String is palindrome inwards Java? (solution)
  • How to detect a missing publish inwards a sorted array? (solution)
  • How to calculate factorial using recursion too iteration? (solution)
  • How produce you lot contrary give-and-take of a judgement inwards Java? (solution)
  • How to detect duplicate characters from String inwards Java? (solution)
  • How to contrary an int variable inwards Java? (solution)
  • How to depository fiscal establishment check if a yr is a bound yr inwards Java? (answer)
  • Write code to implement Bubble sort algorithm inwards Java? (code)
  • Top 10 Programming problems from Java Interviews? (article)
  • Write code to implement Quicksort algorithm inwards Java? (algorithm)
  • How produce you lot swap ii integers without using temporary variable? (solution)
  • Write a plan to depository fiscal establishment check if a publish is ability of ii or not? (solution)
  • How to contrary String inwards Java without using StringBuffer? (solution)
  • Write a plan to code insertion sort algorithm inwards Java (program)


Books for Coding Interviews
Cracking the Coding Interview: 150 Programming Questions too Solutions
Programming Interviews Exposed: Secrets to Landing Your Next Job

Subscribe to receive free email updates:

0 Response to "2 Ways to uncovering duplicate elements inwards an Array - Java"

Posting Komentar