Remove Duplicates from Sorted Array in Python

PythonServer Side ProgrammingProgramming

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]
  • return length

Let us see the implementation to get a better understanding

Example (Python)

 Live Demo

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
raja
Published on 08-Jan-2020 15:11:03
Advertisements