Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk2 min

How to Remove Duplicates from a Sorted Array in Python

A read pointer and write pointer remove repeats from a sorted Python list in one pass while returning the length of the valid unique-value prefix.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a read pointer to scan the sorted list and a write pointer to build the unique-value prefix. The function below keeps one copy of each value in place and returns the length k of the valid prefix; it does not physically shorten the list.

In-place solution for one copy of each value

This is the contract in LeetCode problem 26: the input is sorted in non-decreasing order, and the first k positions must contain the unique values in sorted order. The remaining positions can be ignored.

As an Amazon Associate I earn from qualifying purchases.

def remove_duplicates(nums):
    if not nums:
        return 0

    write = 1
    for read in range(1, len(nums)):
        if nums[read] != nums[write - 1]:
            nums[write] = nums[read]
            write += 1

    return write

For example, given [1, 1, 2, 2, 3], the function returns 3, and the first three positions contain [1, 2, 3]. The list may still have five positions; only the prefix of length k is part of the result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the read and write pointers work

  • read visits each input position from left to right.
  • write marks the next position where a new, unique value should go.
  • Because equal values are adjacent in a sorted list, comparing the current value with nums[write - 1] is enough to detect whether it has already been retained.
  • When the values differ, the current value is copied to nums[write], and write advances.

At the end, write is the number of retained values. The algorithm scans the list once, taking O(n) time and O(1) auxiliary space for an ordinary mutable Python list.

What the return value means

The returned value k is the length of the answer, not a new list. The problem specification says, “The first k elements of nums should contain the unique numbers in sorted order.” The tail after that prefix is unspecified and should not be treated as part of the result.

If your own code needs a physically shorter list, delete the unused tail after calling the function:

k = remove_duplicates(nums)
del nums[k:]

That deletion is an additional choice for your Python API; it is not required by the in-place prefix contract.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Edge cases

  • An empty list returns 0. This is a useful extension for Python callers, even though the reference problem lists nonempty inputs.
  • A singleton list returns 1.
  • An all-equal list returns 1.
  • An already-unique list returns its original length.

When to use itertools.groupby instead

itertools.groupby groups consecutive elements with equal keys and assumes the input is already sorted on that key, as described in the Python Functional Programming HOWTO. It can produce a new list of unique values concisely:

from itertools import groupby

unique = [key for key, _ in groupby(nums)]

This creates a separate output list rather than rewriting the input prefix. Use it when a new collection is what you need; use the pointer method when the required result is an in-place prefix and a returned length.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Do not confuse this with the at-most-two variation

LeetCode problem 80 asks for a different result: retain each value at most twice. Its keep condition compares a candidate with the value two positions behind the write pointer, once two values have already been retained. That is not the condition for problem 26, which keeps exactly one copy of each value.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.