Given an array {7, 1, 3, 2, 2, 4, 4, 5, 1}, write a program (java) that will match the first duplicate and return

Solution:

We would use a Set since it is primarily optimized for testing membership. Worst time is order of n.

import java.util.HashSet;
import java.util.Set;

public class FindFirstDuplicate {

 public static void main(String[] args)
 {
  int array[] = {
    1, 7, 1, 3, 2, 2, 4, 4, 5, 1
  };
  int firstDuplicate = matchFirstDuplicate(array);

  if (firstDuplicate == -1)
   System.out.println("No duplicates");
  else
   System.out.println("Duplicate found: " + firstDuplicate);

 }

 public static int matchFirstDuplicate(int[] array)
 {
  Set<Integer> dupMap = new HashSet<Integer>();
  
  for (int i : array) {
   if (dupMap.contains(i)) {
    return i;
   }
   else {
    dupMap.add(i);
   }
    
  }
  return -1;

 }

}

Leave a Reply

Your email address will not be published. Required fields are marked *

     

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">