Problem 286424 · easy · Phase 02 Linear Data Structures

Collapse Runs in a Sorted List

linked list · deletion · sorted

Given the head of a singly linked list whose values are sorted in non-decreasing order, remove nodes so that every value appears exactly once, and return the head. Keep the first node of each run of equal values.

Examples

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

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

Constraints

  • 0 <= number of nodes <= 10**4
  • The list is sorted
  • Target: O(n) time, O(1) extra space, no extra data structures

Goals

  • Compare a node with its successor
  • Decide when to advance and when to unlink
Starting Python…