Remove Duplicates from Sorted Array II

Medium · Two Pointers · Array · Two Pointers

Problem

You are given an integer array nums sorted in non-decreasing order. Edit it in place so that each distinct value appears at most twice, keeping the relative order of what remains, and return k, the number of elements kept.

The first k positions of nums must hold the result, in order; whatever is left after them is ignored. Use O(1) extra memory: do not build a second array.

The grader checks the returned k and nums[:k].

Examples

Input: nums = [1,1,1,2,3,3,3,3]
Output: k = 5, nums[:5] = [1,1,2,3,3]

The run of three 1s and the run of four 3s are each cut to two copies. The 2 stays.

Input: nums = [4,5,6]
Output: k = 3, nums[:3] = [4,5,6]

No value appears more than twice, so nothing moves.

Input: nums = [9,9,9]
Output: k = 2, nums[:2] = [9,9]

The third 9 is dropped. What sits in nums[2] afterwards does not matter.

Constraints

Approaches

Follow-up

What if each value may appear at most m times? Compare with nums[k - m] instead of nums[k - 2]; the proof is the same. And if the array were not sorted, copies would no longer be adjacent, so you would need a count per value (a hash map) and the order of first appearances.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…