26. Remove Duplicates from Sorted Array

Detail explanation for two-pointer, runtime 79.28 %

Xu LIANG
LeetCode Cracker
2 min readMar 28, 2019

--

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Example 2:

Solution 1: two-pointer

The idea for such a problem is that we will set two pointers, the faster one will go through all elements in the list, and the slower one only move when meeting the unique number.

Not bad, but wait, why this pass all the tests! The question told us to remove the duplicates in-place such that each element appear only once, But we can see after the for loop, nums looks like below.

I think this is just the test case created by LeetCode is not enough. So we still need to delete the duplicates in-place. But this time it will become much easier.

--

--

Xu LIANG
LeetCode Cracker

I’m an engineer focusing on NLP and Data Science. I write stuff to repay the engineer community. You can find me on linkedin.com/in/xu-liang-99356891/