File: remove-duplicates-from-sorted-array/solution.py

Date: 2026-06-06

Time: 18:45

Purpose

This file implements LeetCode Problem #26 — "Remove Duplicates from Sorted Array." It owns the in-place deduplication of a sorted integer array, returning the count of unique elements. The solution modifies nums so that the first k positions contain the unique values in order, and the caller can ignore everything past index k-1.

Key Components

Solution.removeDuplicates(self, nums: List[int]) -> int

The sole method. Contract:

Patterns

Two-pointer / read-write head pattern. k is the write pointer (also doubles as the count of unique elements found so far). i is the read pointer scanning forward through the array. When nums[i] differs from the last written value (nums[k-1]), it gets written to nums[k] and k advances.

This is the canonical in-place deduplication idiom — O(n) time, O(1) extra space. The comparison nums[i] != nums[k - 1] works because the array is sorted: duplicates are always contiguous, so comparing against the last written value is sufficient.

Dependencies

Flow

1. k starts at 1 — the first element is always unique by definition.

2. i iterates from index 1 to len(nums) - 1.

3. At each step, compare nums[i] (current read position) against nums[k - 1] (last unique value written).

4. If they differ, copy nums[i] to nums[k] and increment k.

5. Return k.

For [1, 1, 2, 3, 3]: k=1 → skip 1 → write 2 at [1], k=2 → write 3 at [2], k=3. Result: [1, 2, 3, *, *], returns 3.

Invariants

Error Handling

None. No bounds checking, no empty-list guard, no type validation. This follows LeetCode convention where inputs are guaranteed to satisfy constraints.

Topics to Explore

Beliefs