• 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 2021
  • 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

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

Aniruddha Chaudhari/8970/4
CodePython
YouTube CSEstack

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 languages 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 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(msg)
out= ""
for ch in msg:
    ind = ord(ch) - ord('a')
    if li[ind] == 0:
       out=out+ch
       li[ind] = 1

print(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 the 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!

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. Sort Circular Rotated Array
  12. Min Arrow to Burst Bubbles
  13. HourGlass with Largest Sum
  14. Max Profit by Buying/Selling Stocks
  15. Hailstone Sequence
  16. Reverse String without affecting Special Characters
  17. Secure Conversation by Encry/Decry
  18. Special Elements in Matrix
  19. Next Greater No with Same set of Digits
  20. Smallest Subarray with Sum Greater than Given Number
  21. Group Anagrams
  22. Find Duplicates in Array in O(n)
  23. Find Two Unique Numbers from Array in O(n)
  24. Number Patterns & Finding Smallest Number
  25. Minimum Cost of Merging Files [Amazon]
  26. Minimum Distance for Truck to Deliver Order [Amazon]
  27. Minimum Coins Required
  28. Max Sum Subarray
  29. Merge Overlapping Intervals
  30. Longest Balanced Subarray
  31. Longest Path in a Weighted Tree
  32. Generate Balanced Parentheses
  33. PostOrder Traversal Without Recursion

© 2021 – 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