- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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
Advertisements