Jayakrishna14

Optimal Way to remove duplicates in sorted array

Sep 16th, 2025
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.37 KB | None | 0 0
  1. def removeDuplicates(l):
  2.     n = len(l)
  3.     i = 0
  4.     j = 0
  5.    
  6.     while j < n:
  7.         cur = l[j]
  8.         while j < n and l[j] == cur:
  9.             j += 1
  10.         l[i] = cur
  11.         i += 1
  12.        
  13.     toRemove = n - i
  14.     for _ in range(toRemove):
  15.         l.pop()
  16.        
  17.  
  18. l = [9, 9, 7, 7, 3, 1]
  19. removeDuplicates(l)
  20. print(*l)
  21.  
  22. # Output: [9, 7, 3, 1]
Advertisement
Add Comment
Please, Sign In to add comment