Remove Duplicates from Sorted Array II
You get an array of numbers sorted from smallest to largest. Rewrite it in place so that every number appears at most twice, keeping the order, and return how many numbers are left; whatever lies after them does not matter. Our example: [1, 1, 1, 2, 2, 3, 3, 3, 3] → 6, and the array starts with [1, 1, 2, 2, 3, 3].
- input
nums: integers in non-decreasing order, so equal ones stand together.- returns
k, how many numbers stay when each number is kept at most twice. Changenumsin place so that its firstkitems are those numbers, in their order; what is left after them does not matter.- constraints
- 1 ≤ nums.length ≤ 3 · 10⁴
- −10⁴ ≤ nums[i] ≤ 10⁴
- nums is in non-decreasing order
- examples
- Open a test in the tests panel: it shows the input and the expected answer.
/**
* @param {number[]} nums
* @return {number}
*/
function removeDuplicates(nums) {
}
Ctrl ↵
format
reset
saved in this browser
Stuck?
See the solution run step by step on our example, then why it works and its complexity.
Next: more two pointers problems
- 125Valid PalindromeEasysolve
- 26Remove Duplicates from Sorted ArrayEasysolve
- 283Move ZeroesEasysolve
- 88Merge Sorted ArrayEasysolve
- 27Remove ElementEasysolve
- 392Is SubsequenceEasysolve
- 167Two Sum II - Input Array Is SortedMediumsolve
- 153SumMediumsolve
- 11Container With Most WaterMediumsolve
- 189Rotate ArrayMediumsolve
- 151Reverse Words in a StringMediumsolve
- 5Longest Palindromic SubstringMediumsolve
- 42Trapping Rain WaterHardsolve
The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.