Two Pointers Rearranging in place

164. Remove Duplicates from Sorted Array

Easy

You are given an array of integers nums sorted in non-decreasing order, so each element is greater than or equal to the one before it. Some values appear more than once. Remove the extra copies so that each value appears only once.

Change nums itself. Return k, the number of distinct values, and leave those k values in the first k positions of nums, in the order they appear. What nums holds after the first k positions does not matter.

The output shows the first k elements of nums after your function returns.

Aim for a single pass over the array with only O(1) extra memory.

Example 1

Input: nums = [1, 1, 2, 3, 3, 3, 7]

Output: [1,2,3,7]

Explanation: The distinct values are 1, 2, 3 and 7. The function returns 4, and the first four elements of nums are [1,2,3,7].

Example 2

Input: nums = [-4, -4, 0, 0, 0]

Output: [-4,0]

Explanation: Negative values and zero are kept like any other value. The function returns 2.

Example 3

Input: nums = [9, 9, 9, 9]

Output: [9]

Explanation: Every element holds the same value, so the function returns 1.

Check your understanding

Work out the answer for this input before you write any code.

nums = [-3, -3, 0, 0, 0, 4]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums is sorted in non-decreasing order.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.