Arrays · Coding problem

Remove Duplicates from Sorted Array

A free coding problem from the In-Place Manipulation skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

nums is sorted, so equal values sit next to each other. Squeeze out the repeats in place, so the first k slots of nums hold each distinct value once, in their original order, and report k. Whatever is left after index k doesn't matter.

Output format

Print the first k values, space-separated.

Example

Input:  nums = [-3, -3, 0, 2, 2, 2, 9]
Output: -3 0 2 9

Here k = 4.

Solve it in a single pass with O(1) extra space, without allocating a second array.

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • -100 <= nums[i] <= 100
  • nums is sorted ascending

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in In-Place Manipulation

Solve it Remove Duplicates from Sorted Array free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime