DSA AnimatorREVISION VIDEOS
← Back to problems
New

Remove Duplicates from Sorted List — LeetCode 83 video explanation

Given the head of a sorted linked list, delete all duplicates so each value appears once. Return the sorted list.

Loading videos…

DSA Animator › DSA Revision › Linked List › Remove Duplicates from Sorted List

Key moments in the Remove Duplicates from Sorted List video

0:04Problem0:11Example0:15Brute force0:23Key idea0:32Dry run0:46Code0:58Takeaway

What you will learn

Remember: in a sorted list, duplicates are neighbours. Skip the next node instead of moving when values match. The video solves Remove Duplicates from Sorted List (LeetCode 83, Easy) with the Linked List Traversal pattern from the Linked List topic, and you can replay every step in the interactive Remove Duplicates from Sorted List animation.

Remove Duplicates from Sorted List video transcript

Problem

Given the head of a sorted linked list, delete all duplicates so each value appears once. Return the sorted list.

Example

For 1, 1, 2, 3, 3, the result is 1, 2, 3.

Brute force

Copying values into a set and building a new list uses extra space. The list is sorted, so duplicates sit next to each other.

Key idea

Walk with one pointer, current. If the next node has the same value, skip it by linking current to the node after it. Otherwise, move current forward.

Dry run

Current is at the first 1, and the next node is also 1, so skip it. Now the next node is 2, which is different, so move to 2. 2 and 3 differ, so move to 3. The next 3 is a duplicate, so skip it. The list is 1, 2, 3.

Code

In code, loop while current and its next exist. If the values match, set current dot next to current dot next dot next. Otherwise move current, so it's O of n time and O of 1 space.

Takeaway

Remember: in a sorted list, duplicates are neighbours. Skip the next node instead of moving when values match.

More Linked List revision videos

← All 185 DSA revision videos