iq.lab
Python starts when a code cell comes near or you run one
easyTwo pointers target 15 min

Remove duplicates from a sorted list

The list of integers nums is sorted from smallest to largest, so equal values sit next to each other. A value may appear more than once.

Rearrange nums in place (inside the same list, using only a few extra variables) so that its first k positions hold each different value once, smallest first. Here k is the number of different values in the list. Return k.

The tests check the returned k and nums[:k]. Whatever is left from position k onward does not matter.

Example 1
Inputnums = [1, 1, 2, 3, 3]Output3, and nums begins [1, 2, 3]

Three different values: 1, 2 and 3. The two items after them can hold anything.

Example 2
Inputnums = [0, 0, 0, 1, 4, 4, 5]Output4, and nums begins [0, 1, 4, 5]

The three 0s become one 0, and the two 4s become one 4.

Example 3
Inputnums = [2, 3, 7]Output3, and nums stays [2, 3, 7]

No value repeats, so every item stays where it is.

Constraints
  • 0 ≤ len(nums) ≤ 106

  • -109 ≤ nums[i] ≤ 109

  • Each item is at least as large as the item before it.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.