15% off all plans & roadmaps Use code

See plans

Remove Duplicates from Sorted Array II

Updated

TL;DR: Remove extra copies from a sorted array in place so each value appears at most twice, then return the new length. Keep a write index, and copy a value forward only when it differs from the value two slots behind the write index.

Problem

You get an integer array nums sorted in non-decreasing order. Remove some duplicates in place so that each value appears at most twice. Keep the relative order of the elements.

Your function must place the result in the first part of nums, because some languages cannot shrink an array. If k elements remain, the first k slots must hold the final result. The values after index k - 1 do not matter.

Return k after you place the result in the first k slots of nums. Do not allocate another array. Modify the input in place and use O(1) extra memory.

The judge passes your function an input array and an expected array. It checks that your returned k matches the expected length, then compares the first k values one by one.

Example 1

Input: nums = [1,1,1,2,2,3]
Output: 5, nums = [1,1,2,2,3,_]
Explanation: The function returns k = 5. The first five values are 1, 1, 2, 2 and 3. The underscore marks a slot whose value does not matter.

Example 2

Input: nums = [0,0,1,1,1,1,2,3,3]
Output: 7, nums = [0,0,1,1,2,3,3,_,_]
Explanation: The function returns k = 7. The first seven values are 0, 0, 1, 1, 2, 3 and 3. The underscores mark slots whose values do not matter.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.

Constraints that matter

  • n up to 3 * 10^4 rules out the shift-delete brute force on large inputs. In the worst case it moves about 4.5 * 10^8 elements.
  • Values lie between -10^4 and 10^4. A count array indexed by value would be fixed size, but it would ignore the sorted order, which already groups equal values together.
  • The array is sorted, so every run of equal values sits in one block. You only need to compare each value with the last two kept values.
  • O(1) extra memory rules out building a second array. You have to reuse the input slots for the answer.

View on LeetCode

Hints

Hint 1

The input is sorted, so all copies of a value sit next to each other.

Hint 2

The naive in-place move looks for three equal values in a row.

Solution

Intuition

The input is sorted, so all copies of a value sit next to each other. You never have to find copies that are far apart. For each value you read, you only need to decide whether the kept output already has two copies of it.

Picture filling a shelf of boxes from the left, where each label may appear on at most two boxes. The write index is the next empty spot, and checking the box two spots back tells you whether that label is already full.

This is the two pointers pattern for in-place array modification. A read index scans the input. A write index marks the next free slot in the kept prefix, so nums[0..write-1] is a valid answer for everything read so far. Sorting is not needed, because the array is already sorted, and sorting it again would cost O(n log n) for no gain.

Why compare with write - 2? The kept prefix is sorted too, so nums[write - 2] is the smaller of the last two kept values. If the new value equals it, then nums[write - 1] must also equal it, because that value sits between them, so keeping the new value would create three equal values in a row. If the new value differs, it is larger, and keeping it is safe.

Watch the pattern animation

Worked example

Input: nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
Output: 7, with the first 7 slots holding [0, 0, 1, 1, 2, 3, 3]
Explanation: The value 1 appears four times, so two copies must go. The value 0 appears twice and the value 3 appears twice, so both stay. The value 2 appears once. Keeping at most two copies of each value leaves 2 + 2 + 1 + 2 = 7 elements, in their original order.

Approach 1: Brute force: delete the third copy by shifting

The naive in-place move looks for three equal values in a row. When it finds one, it deletes the third copy by shifting every later element one slot left, then shrinks the length. It does not advance the index after a deletion, because a new value may now sit in the same place.

The scan stops when no index starts a triple. Each deletion removes one extra copy, so the result keeps at most two of each value and keeps the order.

Steps

  1. Set n to the array length and i to 0.
  2. While i < n - 2, compare nums[i], nums[i + 1] and nums[i + 2].
  3. If all three are equal, shift nums[i + 3] through nums[n - 1] one slot left.
  4. After the shift, decrease n by 1 and leave i unchanged.
  5. If the three values are not all equal, increase i by 1.
  6. Return n.

Dry run

Start with [0, 0, 1, 1, 1, 1, 2, 3, 3] and n = 9.

  • i = 0: values 0, 0, 1. Not a triple. Move on.
  • i = 1: values 0, 1, 1. Not a triple. Move on.
  • i = 2: values 1, 1, 1. Triple found. Shift the tail left from index 4. The array becomes [0, 0, 1, 1, 1, 2, 3, 3, 3] and n = 8.
  • i = 2 again: values 1, 1, 1. Triple found. Shift the tail left from index 4. The array becomes [0, 0, 1, 1, 2, 3, 3, 3, 3] and n = 7.
  • i = 2: values 1, 1, 2. Not a triple. i = 3: values 1, 2, 3. Not a triple. i = 4: values 2, 3, 3. Not a triple.
  • i = 5 is not less than n - 2 = 5, so the loop stops.

Return 7. The first seven values are [0, 0, 1, 1, 2, 3, 3].

Complexity

TimeO(n^2)
SpaceO(1)

Let n be the array length. Each loop pass either advances i or deletes one copy, and both can happen at most n times, so there are at most 2n passes. A deletion shifts up to n elements, and up to n - 2 deletions can happen when every value is equal, which gives about n^2 / 2 moves in total. The extra space is only the variables n and i.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        n = len(nums)
        i = 0
        while i < n - 2:
            if nums[i] == nums[i + 1] == nums[i + 2]:
                # Shift everything after index i + 2 one place left.
                for j in range(i + 2, n - 1):
                    nums[j] = nums[j + 1]
                n -= 1
            else:
                i += 1
        return n

The In-place Array Modification infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

In-place Array Modification

Part of Two Pointers

Approach 2: Two pointers with a write indexOptimalIn-place Array Modification

What's slow: the brute force changes the array again and again. Each deletion copies the whole tail, so the same values move many times.

The insight that fixes it: you never need to delete. Copy each value you keep into the next free slot at the front, in one pass. The write index does the work of all those shifts.

The rule is simple to state. Keep nums[read] when it differs from nums[write - 2], and skip it otherwise. Every kept value lands at or before its read position, so no unread value gets overwritten.

Steps

  1. If the length is 2 or less, return the length.
  2. Set write to 2. The first two slots are always valid.
  3. For read from 2 to the end, compare nums[read] with nums[write - 2].
  4. If they differ, copy nums[read] into nums[write] and increase write by 1.
  5. If they are equal, skip the value and change nothing.
  6. Return write.

Dry run

Start with [0, 0, 1, 1, 1, 1, 2, 3, 3] and write = 2. The table shows the kept prefix after each step.

Stepreadnums[read]nums[write - 2]DecisionwriteKept prefix
start---first two slots are kept2[0, 0]
1210differs, copy to index 23[0, 0, 1]
2310differs, copy to index 34[0, 0, 1, 1]
3411equal, skip4[0, 0, 1, 1]
4511equal, skip4[0, 0, 1, 1]
5621differs, copy to index 45[0, 0, 1, 1, 2]
6731differs, copy to index 56[0, 0, 1, 1, 2, 3]
7832differs, copy to index 67[0, 0, 1, 1, 2, 3, 3]

The loop ends with write = 7, so return 7. The first seven values are [0, 0, 1, 1, 2, 3, 3], which matches the expected output.

Complexity

TimeO(n)
SpaceO(1)

Let n be the array length. The read index runs from 2 to n - 1, so the loop body runs n - 2 times. Each pass does one comparison, at most one copy and one increment, which takes constant time. The extra space is two integer indexes, and the read index always stays at or ahead of the write index, so no unread value is overwritten.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        if len(nums) <= 2:
            return len(nums)
        # The first two slots are always valid.
        write = 2
        for read in range(2, len(nums)):
            # nums[write - 2] is the value two places back in the kept prefix.
            if nums[read] != nums[write - 2]:
                nums[write] = nums[read]
                write += 1
        return write

Common mistakes

  • if nums[read] != nums[read - 2] compares against the original array, not the kept prefix. Compare against nums[write - 2], because the prefix is what you are building.
  • if nums[read] != nums[write - 1] is the rule from the single-copy version. It rejects every second copy. Use write - 2 so that two copies survive.
  • Returning write without the length guard. For nums = [7], the loop never runs and write stays 2, so the answer is wrong. Return the length first when it is 2 or less.
  • In the shift-delete brute force, increasing i right after a deletion. The value that moved into index i + 2 is never checked, so a triple can slip through. Leave i unchanged after a deletion.
  • Returning len(nums) in Python or nums.length in Java at the end. The length never changes in the write-index solution, so the answer is always the original length. Return write.

Edge cases

  • nums = [1] returns 1 and leaves the array unchanged.
  • nums = [1, 1] returns 2 and leaves the array unchanged.
  • nums = [1, 1, 1] returns 2, and the first two slots hold 1 and 1.
  • nums = [5, 5, 5, 5, 5] returns 2, and the first two slots hold 5 and 5.
  • nums = [-3, -3, -3, -2] returns 3, and the first three slots hold -3, -3 and -2. Negative values need no special handling.
  • nums = [1, 2, 3] returns 3, because no value repeats and nothing is removed.
  • An array of length 3 * 10^4 with each value repeated three times returns 2 * 10^4. The write index visits each element once, so it stays fast.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Remove Duplicates from Sorted Array II, with how to answer them.

Unlock the follow-ups

Remove Duplicates from Sorted Array II FAQ

What is the time complexity of Remove Duplicates from Sorted Array II?

The two pointers solution runs in O(n) time, because the read index visits each element once. The shift-delete brute force runs in O(n^2) time, because each deletion can move up to n elements.

Why use two pointers for Remove Duplicates from Sorted Array II?

The read pointer scans the input, and the write pointer marks the end of the valid prefix. Two pointers let you keep the answer in the first slots without a second array. Sorting makes the check local, so comparing with nums[write - 2] is enough.

Can Remove Duplicates from Sorted Array II be solved in O(1) extra space?

Yes. The two pointers solution uses two integer indexes and changes the input in place. A hash map of counts would need O(n) extra space, which the problem forbids.

Why compare with nums[write - 2] instead of nums[write - 1]?

Each value may appear twice, so the rule has to look two kept values back. nums[write - 1] only tells you the last kept value, and the new value may match it without making a third copy. Comparing with write - 2 catches the third copy exactly.

Does Remove Duplicates from Sorted Array II require sorting first?

No. The input is already sorted, and the solution relies on that order. Sorting again would cost O(n log n) and would not change the answer.

Asked at

See which companies ask this — Pro

Practise it