Problem Statement:
You have given a string. You need to remove all the duplicates from the string.
The final output string should contain each character only once. The respective order of the characters inside the string should remain the same.
You can only traverse the string at once.
Example:
Input string: ababacd
Output string: abcd
You can use any programming language like C/C++, Java, Python, or anything you are comfortable with…
In Python, we can use the set() method, to remove all the duplicate characters. But it will not preserver the ordering of the character.
print("".join(set("ababacd")))
Output:
acbd
Note: Every time you run this code, you will get a different output. The set operation returns characters in different orders.
Our output should be abcd
.
Here is the solution.
Algorithm:
Prerequisite:
Python Code
msg = " ababacd" li = [0] * 26 print(f"Origional string: {msg}") out= "" for ch in msg: ind = ord(ch) - ord('a') if li[ind] == 0: out=out+ch li[ind] = 1 print(f"Unique characters in string: {out}")
Output:
abcd
Complexity:
You are traversing all the characters in the string only once, it takes linear time i.e. O(n)
where ‘n’ is the length of the string.
It takes extra space to store the flag for all 26 characters. It will be always the same size despite the length of the string. The space complexity will be O(1)
.
What’s next?
This is the simple program to remove all duplicates from a given string in Python.
What are the other solutions you can provide to solve this problem? You can share your solutions in any programming language.
It can be done in this way to.
Looks good.
>>> from collections import Counter
>>> “”.join(list(Counter(‘ababacd’)))
‘abcd’
Interesting!
we could have done this
This is the best one.
expanding on MOHIT’s method; the list is reduntant
>>> from collections import Counter
>>> “”.join(Counter(‘ababacd’))
‘abcd’
Here is my solution. May it helps.
Nice answer bro.
Elegent yet simple.
This solution is simple but it involves time complexity for membership operation. When you are writing it in interview or competitive programming, they expect optimized code in terms of complexity.
could have done
def remove_duplicate_chars(string):
chars = []
for i in string:
if i in chars:
continue
print(i, end=”)
chars.append(i)
remove_duplicate_chars(#whatever you want)