Wednesday, 5 August 2015

Find duplicates from a given list of numbers

We can solve this problem in number of ways.

Without using extra space
If you asked to solve it using without extra space, first sort the list, and apply logic by comparing adjacent elements.

By using extra space
If you are permitted to use extra space, we can solve this problem using HashSet easily. Iterate through the list, try to insert  elements into HashSet, if element is unable to insert into HashSet, then it is duplicate.
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class Elements<T extends Comparable<T>> {

 public Set<T> getDuplicates(List<T> data) {
  Objects.nonNull(data);

  Set<T> set = new HashSet<>();
  Set<T> duplicateSet = new HashSet<>();

  for (T temp : data) {
   if (!set.add(temp)) {
    duplicateSet.add(temp);
   }
  }

  return duplicateSet;
 }

}

Following is the junit test case for above program.

import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;

public class ElementsTest {

 @Test
 public void test1() {
  Elements<Integer> ele = new Elements<>();

  List<Integer> data = Arrays.asList(1, 2, 3, 4, 5, 6, 2, 3, 4, 7, 8);
  Set<Integer> duplicates = ele.getDuplicates(data);
  Set<Integer> expected = new HashSet<>(Arrays.asList(2, 3, 4));

  assertTrue(duplicates.equals(expected));
 }
}



No comments:

Post a Comment