-
-
Save InterviewBytes/43de42fb4c2210b375d93154db9e8ce5 to your computer and use it in GitHub Desktop.
Delete duplicates in linked list. O(n) space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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