Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 8, 2017 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/43de42fb4c2210b375d93154db9e8ce5 to your computer and use it in GitHub Desktop.
Save InterviewBytes/43de42fb4c2210b375d93154db9e8ce5 to your computer and use it in GitHub Desktop.
Delete duplicates in linked list. O(n) space
package com.interviewbytes.linkedlists;
import java.util.HashMap;
import java.util.Map;
public class DeleteDuplicates {
public ListNode deleteDuplicates(ListNode head) {
Map<Integer, Integer> countMap = new HashMap<>();
ListNode current = head;
while (current != null) {
countMap.put(current.val, countMap.getOrDefault(current.val, 0) + 1);
current = current.next;
}
ListNode sentinel = new ListNode(0);
current = sentinel;
while (head != null) {
if (countMap.get(head.val) == 1) {
current.next = head;
current = current.next;
}
head = head.next;
}
current.next = null;
return sentinel.next;
}
}
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment