Problem 247691 · medium · Phase 02 Linear Data Structures

Remove Repeats From an Unsorted List

linked list · deletion · set

Given the head of a singly linked list whose values are in no particular order, remove every node whose value has already appeared earlier in the list, so that the first occurrence of each value is kept in its original order. Return the head.

Examples

Input:  head = 3 -> 1 -> 3 -> 2 -> 1
Output: 3 -> 1 -> 2

Input:  head = 1 -> 1 -> 1
Output: 1

Constraints

  • 0 <= number of nodes <= 10**4
  • Target: O(n) time, O(n) extra space, one pass

Goals

  • Use a set to remember values already kept
  • Unlink repeated nodes while keeping the original order
Starting Python…