← Back to Leo Academy Masterclass

Problem #26: Remove Duplicates from Sorted Array

Easy Array & String

Intuition & Strategy Breakdown

Use two pointers (write index and read index). Iterate through the sorted array, and whenever a new element is encountered, copy it to the write index and increment write index.

Python Solution

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

Java Solution

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int l = 1;
        for (int r = 1; r < nums.length; r++) {
            if (nums[r] != nums[r - 1]) {
                nums[l++] = nums[r];
            }
        }
        return l;
    }
}
Watch Interactive Video on Leo Academy Main App