Remove Duplicates from Sorted Array II

Given an integer array nums sorted in non-decreasing order, remove duplicates in place so that each distinct value appears at most twice, keeping the relative order. Put the kept values in the first k slots of nums and return k. Use O(1) extra memory.

30:00

Remove Duplicates from Sorted Array II
medium
Free written solution
Topics
Companies

Given an integer array nums sorted in non-decreasing order, remove duplicates in place so that each distinct value appears at most twice, keeping the relative order. Put the kept values in the first k slots of nums and return k. Use O(1) extra memory.

Example 1:
Input: {"nums":[1,1,1,2,2,3]}
Output: [1,1,2,2,3]
Constraints:
  • 1≤nums.length≤3×1041 \leq \text{nums.length} \leq 3 \times 10^4

  • −104≤nums[i]≤104-10^4 \leq \text{nums}[i] \leq 10^4

  • nums is sorted in non-decreasing order.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,1,1,2,2,3]}

k = 0 marks the end of the kept prefix. Every value may appear at most twice in it, so each new value is checked against nums[k - 2].

nums (in place)

1
1
1
2
2
3

0

1

2

3

4

5

last two kept vs incoming

·

k-2

·

k-1

←

·

nums[i]

counts

kept k = 0

dropped = 0

Variables
VariableValue
k0
n6
DepthFunction Call
Stack empty
0/14