Remove Duplicates from a Sorted Array using Python

Removing duplicate values from a sorted array is one of the popular coding interview questions. It is asked in coding interviews by companies like FAANG many times. Here you need to return an array of unique values by removing all the duplicate values from a sorted array. So, if you want to learn how to remove duplicates from a sorted array, this article is for you. In this article, I will take you through how to remove duplicates from a sorted array using Python.

Remove Duplicates from a Sorted Array using Python

To solve the problem of removing duplicates from a sorted array, you need to create a new array by only storing the unique values from the input array. For example, look at the input and output array mentioned below:

  1. Input Array: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
  2. Output Array: [0, 1, 2, 3, 4]

So the input array will have duplicate values in sorted order, and the output array should only have unique values.

I hope you understood what removing duplicates from a sorted array means. Now here’s how to solve this problem using the Python programming language:

def removeDuplicate(items):
    list1 = []
    for i in items:
        if i not in list1:
            list1.append(i)
    return list1

nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
print(removeDuplicate(nums))
Output: [0, 1, 2, 3, 4]

So this is how you can remove duplicate values from a sorted array using Python. You can find many more practice questions to improve your problem-solving skills using Python here.

Summary

To solve the problem of removing duplicates from a sorted array, you need to create a new array by only storing the unique values from the input array. I hope you liked this article on removing duplicates from a sorted array using Python. Feel free to ask valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1433

Leave a Reply