Open In App

Remove All Duplicates from a Given String in Python

Last Updated : 07 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a string and we need to remove all duplicates from it. What will be the output if the order of character matters? Examples:

Input : geeksforgeeks 
Output : geksfor

This problem has an existing solution please refer to Remove all duplicates from a given string

Method 1: 

Python
from collections import OrderedDict 

# Function to remove all duplicates from string 
# and order does not matter 
def removeDupWithoutOrder(str): 

    # set() --> A Set is an unordered collection 
    #         data type that is iterable, mutable, 
    #         and has no duplicate elements. 
    # "".join() --> It joins two adjacent elements in 
    #             iterable with any symbol defined in 
    #             "" ( double quotes ) and returns a 
    #             single string 
    return "".join(set(str)) 

# Function to remove all duplicates from string 
# and keep the order of characters same 
def removeDupWithOrder(str): 
    return "".join(OrderedDict.fromkeys(str)) 

# Driver program 
if __name__ == "__main__": 
    str = "geeksforgeeks"
    print ("Without Order = ",removeDupWithoutOrder(str)) 
    print ("With Order = ",removeDupWithOrder(str)) 

Output
Without Order =  okergsf
With Order =  geksfor

Time complexity: O(n)
Auxiliary Space: O(n)

Method 2: 

Python
def removeDuplicate(str):
    s = set(str)
    s = "".join(s)
    print("Without Order:", s)
    
    t = ""
    for i in str:
        if i in t:
            pass
        else:
            t = t + i
            
    print("With Order:", t)

str = "geeksforgeeks"
removeDuplicate(str)

Output
Without Order: soerkgf
With Order: geksfor

Time complexity: O(n)
Auxiliary Space: O(n)

What do OrderedDict and fromkeys() do?

An OrderedDict is a dictionary that remembers the order of the keys that were inserted first. If a new entry overwrites an existing entry, the original insertion position is left unchanged.

For example, see below code snippet : 

Python
from collections import OrderedDict 

ordinary_dictionary = {} 
ordinary_dictionary['a'] = 1
ordinary_dictionary['b'] = 2
ordinary_dictionary['c'] = 3
ordinary_dictionary['d'] = 4
ordinary_dictionary['e'] = 5

# Output = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} 
print (ordinary_dictionary)     

ordered_dictionary = OrderedDict() 
ordered_dictionary['a'] = 1
ordered_dictionary['b'] = 2
ordered_dictionary['c'] = 3
ordered_dictionary['d'] = 4
ordered_dictionary['e'] = 5

# Output = {'a':1,'b':2,'c':3,'d':4,'e':5} 
print (ordered_dictionary)     

Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)])

Time complexity: O(n)
Auxiliary Space: O(1)

fromkeys() creates a new dictionary with keys from seq and values set to a value and returns a list of keys, fromkeys(seq[, value]) is the syntax for fromkeys() method. Parameters :

  • seq : This is the list of values that would be used for dictionary keys preparation.
  • value : This is optional, if provided then the value would be set to this value.

For example, see below code snippet : 

Python
from collections import OrderedDict
seq = ('name', 'age', 'gender')
dict = OrderedDict.fromkeys(seq)

# Output = {'age': None, 'name': None, 'gender': None}
print (str(dict)) 
dict = OrderedDict.fromkeys(seq, 10)

# Output = {'age': 10, 'name': 10, 'gender': 10}
print (str(dict))       

Output
OrderedDict([('name', None), ('age', None), ('gender', None)])
OrderedDict([('name', 10), ('age', 10), ('gender', 10)])

Time complexity: O(n)
Auxiliary Space: O(1)

Method 5: Using operator.countOf() Method

Python
import operator as op


def removeDuplicate(str):
    s = set(str)
    s = "".join(s)
    print("Without Order:", s)
    t = ""
    for i in str:
        if op.countOf(t, i) > 0:
            pass
        else:
            t = t+i
    print("With Order:", t)


str = "geeksforgeeks"
removeDuplicate(str)

Output
Without Order: rfogesk
With Order: geksfor

Time Complexity: O(N)
Auxiliary Space : O(N)



Similar Reads

Python | Remove all duplicates words from a given sentence
Given a sentence containing n words/strings. Remove all duplicates words/strings which are similar to each others. Examples: Input : Geeks for Geeks Output : Geeks for Input : Python is great and Java is also great Output : is also Java Python and great We can solve this problem quickly using python Counter() method. Approach is very simple. 1) Spl
7 min read
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 = geeksforgeeksOutput: geksforExplanati
2 min read
Remove all consecutive duplicates from the string
Given a string S, The task is to remove all the consecutive duplicate characters of the string and return the resultant string. Note: that this problem is different from Recursively remove all adjacent duplicates. Here we keep one character and remove all subsequent same characters. Examples: Input: S= "aaaaabbbbbb"Output: ab Input: S = "geeksforge
14 min read
Remove All Adjacent Duplicates in String II
Given a string s and an integer k, the task is to repeatedly delete k adjacent duplicates till no deletions are possible and then return the final string. On deletion of k adjacent duplicates, the left and right sides of the deleted substring is concatenated together. Examples: Input: s = "abcd", k = 2Output: "abcd"Explanation: There's nothing to d
3 min read
Minimum number of insertions in given String to remove adjacent duplicates
Given a string str of size N, the task is to find the minimum number of additions in the string such that no two consecutive elements are the same. Examples: Input: str="rrg" Output: 1Explanation: Add an element between two r's Input: str="rrrrr"Output: 4 Approach: The above problem can be solved using the below given steps: Declare variable min_st
4 min read
C# Program To Remove Duplicates From A Given String
Write a C# 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 = geeksforgeeksOutput: geksforExplanation:
3 min read
Java Program To Remove Duplicates From A Given String
Write a java program for a given string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. Note: The order of remaining characters in the output should be the same as in the original string.Example: Input: Str = geeksforgeeksOutput: geksforExplanation: After removing du
3 min read
C++ Program To Remove Duplicates From A Given String
Write a C++ program for a given string S, the task is to remove all the duplicates in the given string. Below are the different methods to remove duplicates in a string. Note: The order of remaining characters in the output should be the same as in the original string.Example: Input: Str = geeksforgeeksOutput: geksforExplanation: After removing dup
3 min read
Remove duplicates from a given string
Given a 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 = geeksforgeeksOutput: geksforExplanation: After removing duplica
9 min read
Javascript Program To Remove Duplicates From A Given String
Write a javascript 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 = geeksforgeeksOutput: geksforExpla
3 min read
Article Tags :
Practice Tags :