Skills101
← All coding problems

Remove Duplicates from Sorted List

easyLinked List & Stack II+10 XPTime limit 2s

A linked list is sorted in non-decreasing order, so equal values sit next to each other. Delete the extra copies so that every value appears exactly once, and print the list.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: one sorted list.

Output: the list without duplicates (empty if it has no nodes).

Constraints: 0 ≤ n ≤ 10⁵, −1000 ≤ value ≤ 1000.

Think about it: walk with one pointer cur. While cur.next has the same value as cur, skip it with cur.next = cur.next.next; otherwise move cur forward. One pass, O(1) extra memory.

Sample input 1

5
1 1 2 3 3

Sample output 1

1 2 3

Sample input 2

3
4 4 4

Sample output 2

4

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.