DEV Community

realNameHidden
realNameHidden

Posted on

Scenario based java interview question

Finding Duplicates in a List
Question: You have a list of integers, and you want to find any duplicates in that list.
 Which collection would you use for efficient duplicate detection?
Answer: I would use a HashSet to track seen integers while iterating through the list. 
If an integer already exists in the HashSet, it is a duplicate. 
Here's how you could implement this:

package com.example.demo;

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

public class Test {
 public static void main(String[] args) {
  List<Integer> li = Arrays.asList(12,12,1,2,3,4,2,4);
  HashSet<Integer> hs = new HashSet<>();
  for(Integer i : li) {
   if(hs.contains(i)) {
    System.out.println(i);
   }
   hs.add(i);
  }
 }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)