Open In App

Python Program To Remove Duplicates From A Given String

Write a Python program for a given string S which may contain lowercase and uppercase characters. The task is to remove all duplicate characters from the string and find the resultant string.

Note: The order of remaining characters in the output should be the same as in the original string.
Example:



Input: Str = geeksforgeeks
Output: geksfor
Explanation: After removing duplicate characters such as e, k, g, s, we have string as “geksfor”.

Input: Str = HappyNewYear
Output: HapyNewYr
Explanation: After removing duplicate characters such as p, e, a, we have string as “HapyNewYr”.



Naive Approach:

Iterate through the string and for each character check if that particular character has occurred before it in the string. If not, add the character to the result, otherwise the character is not added to result.

 
Below is the implementation of above approach:




string = "geeksforgeeks"
p = ""
for char in string:
    if char not in p:
        p = p+char
print(p)
k = list("geeksforgeeks")

Output
geksfor



Time Complexity : O(n * n) 
Auxiliary Space : O(1) , Keeps order of elements the same as input. 

Remove duplicates from a given string using Hashing

Iterating through the given string and use a map to efficiently track of encountered characters. If a character is encountered for the first time, it’s added to the result string, Otherwise, it’s skipped. This ensures the output string contains only unique characters in the same order as the input string.

Below is the implementation of above approach:  




# Python program to create a unique string using unordered_map
 
# access time in unordered_map on is O(1) generally if no collisions occur
# and therefore it helps us check if an element exists in a string in O(1)
# time complexity with constant space.
 
 
def removeDuplicates(s, n):
    exists = {}
    index = 0
    ans = ""
 
    for i in range(0, n):
        if s[i] not in exists or exists[s[i]] == 0:
            s[index] = s[i]
            print(s[index], end='')
            index += 1
            exists[s[i]] = 1
 
 
# driver code
s = "geeksforgeeks"
s1 = list(s)
n = len(s1)
removeDuplicates(s1, n)

Output
geksfor



Time Complexity: O(n)
Space Complexity: O(1)

Please refer complete article on Remove duplicates from a given string for more details!


Article Tags :