Remove Duplicates from Sorted Array solution explained

To remove duplicates from a sorted array in place, walk the array with a read pointer and keep a write pointer at the end of the deduplicated prefix. Copy a value forward only when it differs from the last value written, then return the write pointer as the new length. That runs in O(n) time with O(1) extra space, and the same idea extends to keeping at most k copies by comparing against the value k positions back.

By Published 7 min read

The problem, in plain terms

You are given an array of numbers sorted from smallest to largest, possibly with repeats. Rearrange it so that the first part of the array lists each distinct value exactly once, in the original sorted order, and return how many distinct values there are. You must do it inside the same array rather than building a new one, and the contents after that count are ignored.

before:  [1, 1, 2, 4, 4, 4, 7, 9, 9]
after:   [1, 2, 4, 7, 9, 4, 7, 9, 9]
return:  5

The first 5 slots are the answer. Slots 5 to 8 still hold
leftovers from the original array, and that is allowed.
A worked example, made up for this page

Worth confirming: the input is sorted in non-decreasing order (not just grouped), it can be empty, and the caller will read only the first k elements. Some interviewers also ask whether the relative order must be kept. With this approach it always is.

What the interviewer is really checking

This is often an early warm-up, and it tests whether you can manage two indexes in one array without tripping over each other. The signals are a clear invariant (everything before the write pointer is the finished answer), correct handling of the first element and the empty array, and an honest O(1) space claim. A follow-up that allows two copies of each value usually comes next, and candidates who stated the invariant clearly can adapt in a minute.

Slower starting ideas

One simple route ignores the in-place rule: put the values into a set, sort the set, and copy it back over the front of the array. That works but uses O(n) extra memory and O(n log n) time, and it throws away the fact that the input was already sorted. Another route stays in place but deletes each duplicate as it is found, shifting everything after it one step left. Each deletion can cost O(n), so an array full of repeats takes O(n²). Both are worth naming in one sentence before moving on, because they show you see what the sorted order buys you.

The optimal approach: a read pointer and a write pointer

Keep write as the length of the deduplicated prefix. The first element is always kept, so write starts at 1. For every later position read, compare nums[read] with nums[write - 1], the last value you kept. If they differ, the value is new: copy it to nums[write] and advance write. If they are equal, skip it. Because write never passes read, you never overwrite a value you still need to look at.

def remove_duplicates(nums):
    if not nums:
        return 0
    write = 1                      # nums[:write] holds the distinct values so far
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1
    return write
Python: one pass, compares each value with the last one kept.
function removeDuplicates(nums) {
  if (nums.length === 0) return 0;
  let write = 1;
  for (let read = 1; read < nums.length; read++) {
    if (nums[read] !== nums[write - 1]) {
      nums[write] = nums[read];
      write++;
    }
  }
  return write;
}
JavaScript: the same loop. The array is changed in place and the count is returned.

Comparing with nums[write - 1] rather than nums[read - 1] gives the same result for this version, since both hold the previous distinct value once a run has started. The write-side comparison is the one that generalizes, which is why it is shown here.

The follow-up: keep at most k copies

A common second question allows each value to appear up to twice (or k times). Only one line changes. A value x should be kept unless the kept prefix already ends with k copies of x, and because the prefix is sorted, that is true exactly when nums[write - k] equals x. The first k elements are always kept.

def keep_at_most(nums, k):
    write = 0
    for x in nums:
        # Keep x unless the kept prefix already ends with k copies of it.
        if write < k or x != nums[write - k]:
            nums[write] = x
            write += 1
    return write
Python: at most k copies of each value. With k = 1 this matches the function above.

On the example array with k = 2, the first 8 slots become 1, 1, 2, 4, 4, 7, 9, 9 and the function returns 8. Iterating with for x in nums while writing into nums is safe here because write never gets ahead of the loop's own position, so every value is read before it could be overwritten.

Complexity summary

n = length of the array
ApproachTimeExtra space
Set, sort, copy backO(n log n)O(n)
Delete each duplicate and shift the rest leftO(n²) worst caseO(1)
Read and write pointersO(n)O(1)
Read and write pointers, at most k copiesO(n)O(1)
n = length of the array. Scroll sideways on a small screen.

Edge cases to test

  • An empty array, which should return 0 without reading nums[0].
  • A single element, which returns 1.
  • No duplicates at all, where every element is copied onto itself.
  • Every element equal, which returns 1.
  • Negative numbers and zero mixed in, to make sure nothing depends on positive values.
  • A long run of one value at the very end, which checks that the loop does not stop early.

Mistakes to avoid

  • Returning the array or a new list when the task asks for the count and an in-place change.
  • Starting write at 0 and comparing with nums[write - 1], which reads index -1 (the last element in Python, undefined in JavaScript).
  • Using a set and claiming O(1) space.
  • Assuming the leftover tail must be cleared or filled. It does not, unless the interviewer says so.
  • In the k-copies version, comparing with nums[read - k] instead of nums[write - k]. The read-side check expects the original value at read - k, but that slot may already have been overwritten. With k = 2 on 2, 2, 2, 3, 3 it keeps only one 3.

How to explain it out loud

Fictional example

A short spoken walkthrough
Candidate
Since the array is sorted, duplicates are next to each other. I'll keep a write index, and everything before it is the deduplicated answer so far.
Candidate
I scan with a read index. If the value differs from the last one I kept, I copy it to the write slot and move write forward. Otherwise I skip it.
Candidate
It's one pass and no extra memory. If you want up to two copies, I'd compare against the value two slots before write instead of one.

Two indexes walking one sorted array also power Squares of a Sorted Array, where they start at opposite ends instead. Writing into an array while still reading from it is the central risk in Merge Sorted Array, which avoids the problem by filling from the back.

Practicing with Natively

Easy problems are where interviewers expect a crisp explanation, so they are good for rehearsing how you talk, not just what you type. When you practice on a Mac or Windows PC, Natively can read the problem from a screenshot, point out an off-by-one in your pointer setup, and keep a transcript of how you described the invariant. See how AI fits into coding interview practice.

Questions people ask

How do you remove duplicates from a sorted array in place?

Keep a write index at the end of the deduplicated prefix and scan with a read index. Copy a value to the write position only when it differs from the last value written, then return the write index as the new length.

What is the time and space complexity?

O(n) time with one pass and O(1) extra space, since only two indexes are stored. Using a set instead costs O(n) extra memory.

Why does the array need to be sorted?

Sorting puts equal values next to each other, so comparing each value with the last kept value is enough to spot a repeat. On unsorted input you would need a set or a sort first.

How do you allow each value to appear at most twice?

Keep a value when fewer than two values have been written or when it differs from the value two positions before the write index. The same rule works for any limit k.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP