
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Duplicates from Sorted Array in Python
Suppose we have a sorted list A. We have to return the length of the array after removing all duplicate entries. We have to perform this in O(1) extra space. So we have to do the operation in-place.
For an example, suppose A = [1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 5, 6] Then the output will be 6, as there are six distinct elements.
To solve this, follow these steps −
- If the list is empty, return 0
- otherwise, initially take prev = first element of A. And define length = 0
- for i := 1 to n-1, do
- if A[i] is not the same as prev, then
- length := length + 1
- prev := A[i]
- if A[i] is not the same as prev, then
- return length
Let us see the implementation to get a better understanding
Example (Python)
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 length = 1 previous = nums[0] index = 1 for i in range(1,len(nums)): if nums[i] != previous: length += 1 previous = nums[i] nums[index] = nums[i] index+=1 return length input_list = [1,1,2,2,2,3,3,3,3,4,5,5,5,6] ob1 = Solution() print(ob1.removeDuplicates(input_list))
Input
[1,1,2,2,2,3,3,3,3,4,5,5,5,6]
Output
6
- Related Questions & Answers
- Remove Duplicates from Sorted Array II in C++
- Remove Duplicates from Sorted List in C++
- Remove Duplicates from Sorted List II in C++
- How to remove duplicates from a sorted linked list in android?
- How to remove duplicates from the sorted array and return the length using C#?
- How to remove duplicates from the sorted array and return the non-duplicated array using C#?
- Removing duplicates from a sorted array of literals in JavaScript
- Python - Ways to remove duplicates from list
- Remove duplicates from a array of objects JavaScript
- Remove duplicates from array with URL values in JavaScript
- C++ Program to Remove Duplicates from a Sorted Linked List Using Recursion
- Java Program to Remove Duplicates from an Array List
- Remove Consecutive Duplicates in Python
- Remove all duplicates from a given string in Python
- Remove array duplicates by property - JavaScript
Advertisements