12 · Two Pointers

#80 Remove Duplicates from Sorted Array II

Mediumsolve on LeetCode ↗

frequently reported atAmazonMetaBloombergMicrosoft

the problem

In plain words

nums is sorted in non-decreasing order. In place, keep at most two copies of each value, in the original order. Return k, the length of the result; nums[0..k) must hold it. Use O(1) extra memory.

in nums = [1,1,1,2,2,3]

out 5, nums = [1,1,2,2,3,_]

in nums = [0,0,1,1,1,1,2,3,3]

out 7, nums = [0,0,1,1,2,3,3,_,_]

  • 1 ≤ n ≤ 3·10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • Sorted non-decreasing

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #26
    2. #27
      Remove Element
      Easyin Two Pointers