Remove Duplicates from Sorted Array

Easy#26same direction

You get a non-empty array of numbers sorted in ascending order. Leave each number once at the start of the same array, in the same order, without a second array, and return how many there are. What lies after them does not matter. Our example: [1, 1, 2, 3, 3, 3, 5] → 4, with [1, 2, 3, 5] at the start.

input
nums: integers in non-decreasing order, so equal ones stand together.
returns
k, the number of different numbers in nums. Change nums in place so that its first k items are those numbers, each once, in their order; what is left after them does not matter.
constraints
  • 1 ≤ nums.length ≤ 3 · 10⁴
  • −100 ≤ nums[i] ≤ 100
  • nums is in non-decreasing order
our 12 tests keep to them
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

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.