Skip to content
How to Remove Duplicates In-Place From a Sorted Array in Python
Fundamentals 3 min read

How to Remove Duplicates In-Place From a Sorted Array in Python

This article explains how to remove duplicates from a sorted array in‑place using Python, detailing the problem constraints, providing two illustrative examples, outlining a simple iteration‑based solution approach, and presenting a complete code implementation that operates with O(1) extra space.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations

Problem Description:

Given a sorted array, remove duplicate elements in‑place so that each element appears only once and return the new length of the array. The operation must use O(1) extra space.

Example

Example 1:

Input: nums = [1,1,2]

Output: 2, and the first two elements of nums become [1,2]. Elements beyond the new length can be ignored.

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]

Output: 5, and the first five elements become [0,1,2,3,4].

Solution Idea

Iterate through the list and remove an element when it is equal to the next one.

Code

class Solution(object):
    def removeDuplicates(self, nums):
        """ 
        :type nums: List[int]
        :rtype: int
        """
        i = 0
        while ( i < len(nums) ):
            if i+2 <= len(nums):
                # the element at i+1 exists
                if nums[i] == nums[i+1]:
                    nums.remove(nums[i])
                    i -= 1
            else:
                return len(nums)
            i += 1
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Algorithmarrayin-placeduplicate removal
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.