Hide sidebar

Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Two Pointers
EasyLeetCode #26
15 min

Problem Statement

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Example

Example 1:

Input: nums = [1,1,2]

nums: [1, 1, 2]

Output: 2, nums: [1,2,_]

Output: 2, nums = [1,2,_]

Solution

The two-pointer approach is efficient for this problem. We use one pointer (`l`) to keep track of the position of the next unique element, and another pointer (`r`) to iterate through the array. If `nums[r]` is different from `nums[l]`, we increment `l` and place `nums[r]` at `nums[l]`.

Algorithm Steps

  • Initialize a left pointer `l` to 0.
  • Iterate through the array with a right pointer `r` starting from index 1.
  • If `nums[r]` is not equal to `nums[l]`, increment `l` and set `nums[l] = nums[r]`.
  • Return `l + 1`.

Remove Duplicates from Sorted Array

Two Pointers Approach

Input: nums = [1, 1, 2]

Output: 1, nums = [1, 1, 2]

Progress1 / 1

Ready to start the visualization

Nums

1
1
2
Remove Duplicates from Sorted Array Solution

class Solution:
    def removeDuplicates(self, nums: list[int]) -> int:
        l = 1
        for r in range(1, len(nums)):
            if nums[r] != nums[r-1]:
                nums[l] = nums[r]
                l += 1
        return l