Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/Python/Coding/Write Python code to remove duplicates from a string.

Write Python code to remove duplicates from a string.

Python/Codingmedium2 min read

Reviewed by Aditya Kumar · Last reviewed 2026-08-08

The most Pythonic and efficient way to remove duplicate characters from a string while preserving their original order is by leveraging dict.fromkeys() or an explicit ordered set like approach. Both…

🤖 Analyze Your Answer
Frequency
Low
Asked at 1 company
Category
179
questions in Python/Coding
Difficulty Split
127E|24M|28H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
EY
Key Concepts Tested
joinpython

Why This Question Matters

This medium-level Python/Coding question appears frequently in data engineering interviews at companies like EY. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (join, python) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
338 wordsIncludes code

The most Pythonic and efficient way to remove duplicate characters from a string while preserving their original order is by leveraging dict.fromkeys() or an explicit ordered set-like approach. Both achieve O(N) time complexity.

Mechanics and Why

Python's dict.fromkeys(iterable) method creates a new dictionary where elements from the iterable become keys. Since dictionary keys must be unique, this naturally deduplicates the characters. Crucially, from Python 3.7+, dictionaries preserve insertion order, making dict.fromkeys() a concise and elegant solution. Converting this dictionary back to a string using ''.join() reconstructs the deduplicated string.

Alternatively, for explicit control or compatibility with older Python versions (pre-3.7), an ordered set-like approach can be used. This involves iterating through the string, adding each character to a set (for O(1) average-case lookup) if it hasn't been seen, and appending it to a list. This ensures both uniqueness and order preservation.

Example and Trade-offs

The dict.fromkeys() method is concise and highly readable. Its time complexity is O(N) because each character is processed once, and dictionary key insertion/lookup is O(1) on average. Space complexity is also O(N) in the worst case (all unique characters).
def dedupe_str(s: str) -> str:
    """Removes duplicate characters from a string, preserving order."""
    return ''.join(dict.fromkeys(s))

For extremely large strings, a generator expression with a set (e.g., seen=set(); ''.join(c for c in s if c not in seen and not seen.add(c))) can be slightly more memory-efficient. This avoids creating an intermediate list or dictionary of the full string's characters before joining, processing characters one by one. This is analogous to how data engineers use generators or iterators to process large datasets without loading everything into memory, similar to processing records in a Kafka topic or rows in a Spark RDD.

In the interview, also mention…

Discuss the importance of order preservation (a common requirement for string deduplication), and how character sets (e.g., Unicode vs. ASCII) don't affect the core logic but might impact memory if characters are multi-byte. Also, consider edge cases like empty strings or strings with only unique characters.
⚡
Pro Tip

Red Flag: Using list+in (O(n²)). Pro-Move: 'dict.fromkeys preserves order—we use for deduping log keys while keeping first occurrence.'

Want all answers as a PDF for offline study?
Seven focused volumes with 750+ in-depth answers — Answer Vault →

Related Python/Coding Questions

easyWhat are traits in Scala, and how are they different from classes?FreemediumWrite a Python function to check if a string is a palindrome.FreeeasyWhat is the difference between a list and a tuple in Python?FreeeasyExplain the difference between shallow copy and deep copy in Python.FreeeasyWrite a Python function to find the first non-repeating character in a string.Free

Level up your prep

Recommended
Educative
Educative Unlimited

800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

Start learning →

Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

According to DataEngPrep.tech, this is one of the most frequently asked Python/Coding interview questions, reported at 1 company. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

← Back to all questionsMore Python/Coding questions →
Categories
All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
By Company
AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
Interview Guides
All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
Products
AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
Company
About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
© 2026 DataEngPrep.tech. All rights reserved.
AboutBlogContactDisclaimer