Bloomberg Interview Question

How to remove duplicates from a linked list

Interview Answers

Anonymous

Dec 29, 2014

To remove duplicates from a list in C++: utilize an unordered_set Go through the list, adding each data element to the set if its not already present. If .find() returns list.end() then you know its not in the list and you can just add the element and continue. If it doesn't return list.end() then that means it's already in the list, in which case you must null the current nodes next pointer and redirect the next pointer of the previous node, to the node which comes after the repeated value node.

Anonymous

Jun 16, 2016

private static LinkedNode removeDuplicate(LinkedNode head) { Map map = new HashMap(); LinkedNode current = head; LinkedNode prev = head; while(current != null) { if(!map.containsKey(current.data)) { map.put(current.data, true); prev = current; current = current.next; } else { current = current.next; prev.next = current; } } return head; }