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.
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 += 1Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
