Remove Duplicates from Sorted Array II
Problem Statement
You are given an integer array nums sorted in non-decreasing order.
Remove extra copies in place so that every value appears at most twice. The elements you keep must stay in their original order. Return k, the number of elements kept.
After your function runs, the first k slots of nums must hold the kept elements in order. Whatever is after slot k β 1 is ignored. Use only O(1) extra memory.
An integer array nums, sorted in non-decreasing order.
An integer k. The judge also checks that nums[0 β¦ kβ1] is the kept elements, in order.
1 appears three times, so one copy is dropped. 2 appears twice and 3 once β both are fine.
1 appears four times, so two copies are dropped. Every other value already appears at most twice.
- β’ 1 β€ nums.length β€ 3 Β· 10^4
- β’ β10^4 β€ nums[i] β€ 10^4
- β’ nums is sorted in non-decreasing order
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Keep an element if the map says fewer than 2 copies are kept; copy back
Count the length of the current run of equal values; keep the first 2 of each run
Keep nums[read] if write < 2 or nums[read] != nums[write β 2]
Walk nums. Keep a map keptCount[value] of how many copies we have kept. If it is below 2, append the element to a new array and increase the count. Copy the new array back into nums.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Two Pointers translate into production architectures and low-level memory mechanics.
Circular Buffer & Ring Queue
Two pointer read/write head synchronization in production memory pools.
Pointers vs References Deep Dive
Pointer arithmetic, dereferencing semantics, and memory layout behind in-place array passes.
const Correctness & East-Const
Passing read-only spans with const int* without copying buffers.