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.
DSA Animator › DSA Revision › Arrays › Remove Duplicates from Sorted Array
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.
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.
For 1, 1, 2, 2, 3, the answer is k equal to 3. The first three slots become 1, 2, 3.
Building a new array of unique values uses O of n extra space. The problem asks you to do it in place.
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.
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.
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.
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.