EasyNo. 0026

Remove Duplicates from Sorted Array — LeetCode 26 Python Solution

Topics
Array, Two Pointers
On a study list
Top Interview 150
Reading time
2 min

The problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.

Example

Example
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}

Python solution

PythonSolution
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k == 0 or x != nums[k - 1]:
                nums[k] = x
                k += 1
        return k

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 26. Remove Duplicates from Sorted Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0080Remove Duplicates from Sorted Array IIMedium
0027Remove ElementEasy
0031Next PermutationMedium
00184SumMedium
00163Sum ClosestMedium
00153SumMedium

Frequently asked questions

How hard is LeetCode 26. Remove Duplicates from Sorted Array?

LeetCode 26. Remove Duplicates from Sorted Array is rated Easy on LeetCode.

What is the time complexity of LeetCode 26. Remove Duplicates from Sorted Array?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 26. Remove Duplicates from Sorted Array?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 26. Remove Duplicates from Sorted Array cover?

LeetCode 26. Remove Duplicates from Sorted Array is tagged Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.