Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Two Pointers

Remove Duplicates From Sorted Array

EASY✓ CHIP-TIMEDLC #26 — FULL STATEMENT

The briefingthe full drill, in my own words

The drill: Compact a sorted array so each value keeps exactly one copy, packed at the front in order, and report how many survived. Judged here on the returned count — the reader-writer packing is the lesson itself.

A sorted array arrives with some values repeated, and the task is to compact it so every distinct value appears exactly once, packed at the front in the same ascending order.

Whatever sits past the compacted prefix doesn't matter — it's never checked. The one required output besides the mutated array is the count of unique values now living at the front.

Because the input is already sorted, every run of a repeated value is contiguous; nothing equal ever appears out of sequence.

  • array length runs from zero up to around thirty thousand
  • values arrive already sorted in non-decreasing order
  • duplicates can repeat any number of times in a row
  • the returned count is the number of unique values now at the front
EX 01
nums = [2, 2, 3, 7, 7, 7, 9]
→ 4
uniques 2, 3, 7, 9
EX 02
nums = [1]
→ 1
single element
EX 03
nums = [5, 5]
→ 1

The hintstake only what you need

HINT 1 THE NUDGE

The array is sorted, so duplicates always sit side by side. A hash set to remember what you've seen is paying for a problem adjacency already solved.

HINT 2 THE STRUCTURE

Keep a boundary: to its left lives the answer built so far. A new value deserves to cross the boundary only if it differs from the last value that did.

HINT 3 ONE STEP FROM THE ANSWER

Reader ahead, writer behind. When the reader's value differs from nums[writer−1], write it there and advance the writer. Where the writer ends up IS the count.

Coach's boardthe pattern, step by step

READER AND WRITERPATTERN · TWO POINTERS, IN-PLACE COMPACTIONnums = [2, 2, 3, 7, 7, 7, 9]
2
2
3
7
7
7
9
STEP 1

Writer w starts at 1; nums[0]=2 is the first unique value, already banked.

STEP 1 / 8 · ← → WORK TOO

The splitstwo paces, two languages

grind/remove-duplicates-from-sorted-array.py — RACE PACE
LANG ▸
PACE ▸
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        w = 1  # nums[:w] is the deduped prefix
        for i in range(1, len(nums)):
            if nums[i] != nums[w - 1]:
                nums[w] = nums[i]
                w += 1
        return w
TIME O(N)SPACE O(1)PYTHON · RACE PACE · 8 LN

✓ CHIP-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED