Interview Question
Team: Algorthims
Country: India
Interview Type: Phone Interview
/// Collection<Object> collection = new ArrayList<Object>();
collection.add("A");
collection.add("B");
collection.add("C");
collection.add("D");
Collection<Object> collection2 = new ArrayList<Object>();
collection2.add("A");
collection2.add("B");
collection2.add("C");
collection2.add("E");
collection.retainAll(collection2);
for (Object str : collection) {
System.out.println(str);
} ///
Collection<Object> collection = new ArrayList<Object>();
collection.add("A");
collection.add("B");
collection.add("C");
collection.add("D");
Collection<Object> collection2 = new ArrayList<Object>();
collection2.add("A");
collection2.add("B");
collection2.add("C");
collection2.add("E");
collection.retainAll(collection2);
for (Object str : collection) {
System.out.println(str);
}
Won't the solutions containing retainAll() or contains() have time complexity O(n^2). Why not use HashMap. Use a HashMap to store the first List and then while taking second List as input, just compare in HashMap whether element is already there or not.
Time complexity: O(n)
That can be done but it would require storage of the HashMap.
When i gave the answer of contains the interviewer asked once u gave me all the common elements in both the lists now give me no similar objects from both the lists.
some thing like A n ( A u B) , ( A u B) n B
the contains solution can handle the same question with a small tweak of removing /flagging the objects in either of the list.
- Niraj Kumar Singh February 28, 2014