DSA AnimatorREVISION VIDEOS
← Back to problems
New

Remove Duplicates from Sorted Array — LeetCode 26 video explanation

Given a sorted array, remove the duplicates in place, so each value appears once. Return k, the number of unique values, with those values in the first k slots.

Loading videos…

DSA Animator › DSA Revision › Arrays › Remove Duplicates from Sorted Array

Key moments in the Remove Duplicates from Sorted Array video

0:04Problem0:15Example0:21Brute force0:28Key idea0:42Dry run1:07Code1:20Takeaway

What you will learn

Remember: a slow write pointer and a fast read pointer compact an array in place. In a sorted array, a value is new exactly when it differs from the last kept value. The video solves Remove Duplicates from Sorted Array (LeetCode 26, Easy) with the Two Pointers pattern from the Arrays topic, and you can replay every step in the interactive Remove Duplicates from Sorted Array animation.

Remove Duplicates from Sorted Array video transcript

Problem

Given a sorted array, remove the duplicates in place, so each value appears once. Return k, the number of unique values, with those values in the first k slots.

Example

For 1, 1, 2, 2, 3, the answer is k equal to 3. The first three slots become 1, 2, 3.

Brute force

Building a new array of unique values uses O of n extra space. The problem asks you to do it in place.

Key idea

Because the array is sorted, duplicates sit next to each other. Keep a write pointer k, which marks the end of the unique part. A read pointer scans ahead, and copies a value forward only when it differs from the last unique one.

Dry run

The first value, 1, is always unique, so k starts at 1. Index 1 is another 1, a duplicate, so we skip it. Index 2 is 2, which is new, so it is written to slot 1, and k becomes 2. Index 3 is 2 again, a duplicate, so we skip it. Index 4 is 3, which is new, so it goes to slot 2, and k becomes 3. The first 3 slots hold 1, 2, 3, and we return 3.

Code

In code, start k at 1. Loop i from 1 to the end. If the value at i differs from the value at k minus 1, write it at k and move k forward. Return k: it's O of n time and O of 1 space.

Takeaway

Remember: a slow write pointer and a fast read pointer compact an array in place. In a sorted array, a value is new exactly when it differs from the last kept value.

More Arrays revision videos

← All 185 DSA revision videos