← Back to Leo Academy Masterclass

Problem #80: Remove Duplicates from Sorted Array II

Medium Array & String

Intuition & Strategy Breakdown

Use two pointers (write and read). Allow at most 2 duplicate occurrences by comparing current element with write-2 index before writing.

Python Solution

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

Java Solution

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