• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Program to Remove All Duplicates Chars from a given String in Python

Aniruddha Chaudhari/18171/10
CodePython

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…

Remove all Duplicates from a given String in Python

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:

  • Create the list of size 26. Initialize all the elements in the list to zero. (This is nothing but the array/list of 26 flags. The first element in the list will be for the character ‘a’, the second element in the list will be for character ‘b’ and so on…).
  • Initialize the output string as an empty string.
  • Loop over all the characters in the given string from right to left.
    • Check the flag value for the given character.
    • If the flag is False (0), the given character is occurring the first time. Append that character to the output string. Set the flag to True (1).
    • If the flag is True (1), don’t do anything.

Prerequisite:

  • Python For Loop
  • Python List

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.

Python Interview Questions eBook

Codecoding challenge
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Suvidh Jain
    August 20, 2020 at 11:56 am

    It can be done in this way to.

    from collections import OrderedDict
    string = input("")
    a = list(OrderedDict.fromkeys(string))
    b = ''.join(a)
    print(b)
    
    • Reply
      Aniruddha Chaudhari
      October 20, 2020 at 2:00 pm

      Looks good.

  • Reply
    MOHIT .
    October 19, 2020 at 2:23 pm

    >>> from collections import Counter
    >>> “”.join(list(Counter(‘ababacd’)))
    ‘abcd’

    • Reply
      Aniruddha Chaudhari
      October 20, 2020 at 2:00 pm

      Interesting!

  • Reply
    Manoj Kumar
    June 30, 2021 at 7:34 pm

    we could have done this

    msg="abcdabedcd"
    print(" ".join(sorted(set(msg))))
    
  • Reply
    Klex
    July 11, 2021 at 7:18 pm

    expanding on MOHIT’s method; the list is reduntant
    >>> from collections import Counter
    >>> “”.join(Counter(‘ababacd’))
    ‘abcd’

  • Reply
    Dassen
    July 16, 2021 at 3:39 pm

    Here is my solution. May it helps.

    a = 'ababacd'
    b = []
    for i in a:
         if i not in b:
             b.append(i)
    
    print("".join(b))
    
    • Reply
      Alister
      October 12, 2021 at 10:29 pm

      Nice answer bro.

    • Reply
      Sahil Kumar Vishwakarma
      February 10, 2022 at 6:23 pm

      Elegent yet simple.

    • Reply
      Aniruddha Chaudhari
      June 28, 2022 at 9:33 am

      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.

Leave a Reply Cancel reply

Why?

Why Competitive Programming Important?

Coding Challenges for Practice

  1. Count Common Factor
  2. Does it Divide
  3. Sum of Sub Arrays
  4. Pair of Desired Sum
  5. Remove Duplicate Char from String
  6. Sort String by Char Freq (Python)
  7. Sort String by Char Freq (Java)
  8. Split Array into Equal Sum Subarray
  9. Validate IP Address
  10. Validate PAN Card Number
  11. Validate Sudoku
  12. Sort Circular Rotated Array
  13. String Permutations
  14. Min Arrow to Burst Bubbles
  15. Min Cost to Paint All Houses [Amazon]
  16. HourGlass with Max Sum
  17. Max Profit by Buying/Selling Stocks
  18. Hailstone Sequence
  19. Reverse String without affecting Special Characters
  20. Secure Conversation by Encry/Decry
  21. Special Elements in Matrix
  22. Next Greater No with Same set of Digits
  23. Smallest Subarray with Sum Greater than Given Number
  24. Group Anagrams
  25. Find Duplicates in Array in O(n)
  26. Find Two Unique Numbers from Array in O(n)
  27. Number Patterns & Finding Smallest Number
  28. First Unique Element in a Stream
  29. Flip Equivalent Binary Trees [TeachMint]
  30. Minimum Cost of Merging Files [Amazon]
  31. Minimum Distance for Truck to Deliver Order [Amazon]
  32. Longest Sequence of URLs
  33. Order Task for Given Dependencies
  34. Design Music Player
  35. Multilevel Parking System Design
  36. Minimum Coins Required
  37. Max Sum Subarray
  38. Max Avg Sum of Two Subsequences
  39. Merge Overlapping Intervals
  40. Longest Balanced Substring
  41. Longest Path in a Weighted Tree
  42. Generate Balanced Parentheses
  43. PostOrder Traversal Without Recursion

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard