DSA problem
Remove Duplicate Characters from a String
Given a string s, remove all duplicate characters and return a string that keeps only the first occurrence of each character, preserving the original order.
Use a hash set (or boolean array) to track which characters have been seen. Iterate through the string: if the current character has not been seen, append it to the result and mark it seen; otherwise skip it. This preserves order and removes duplicates in O(n) time. It is a clean example of the seen-set pattern, used to detect duplicates in streams, deduplicate log entries, and build unique indexes. The key insight: you need both a set (for O(1) lookup) and a result builder (to preserve order), because sets alone do not maintain insertion order in most languages.
Examples
s = "programming""progamin"Constraints
- 1 <= s.length <= 10^5
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.