Remove Duplicates from String - Problem

Given a string, remove all duplicate characters while preserving the order of first appearance.

For example, if the input string is "programming", the output should be "progamin" because we keep the first occurrence of each character and remove subsequent duplicates.

Note: The comparison is case-sensitive, so 'A' and 'a' are considered different characters.

Input & Output

Example 1 — Basic Case
$ Input: s = "programming"
Output: "proga"
💡 Note: Keep first occurrence of each character: p(1st), r(1st), o(1st), g(1st), r(duplicate-skip), a(1st), m(1st), m(duplicate-skip), i(1st), n(1st), g(duplicate-skip) → "progamin"
Example 2 — All Unique
$ Input: s = "abcdef"
Output: "abcdef"
💡 Note: No duplicates found, so the output is the same as input
Example 3 — All Same
$ Input: s = "aaaa"
Output: "a"
💡 Note: Only keep the first 'a', remove the three duplicates

Constraints

  • 1 ≤ s.length ≤ 1000
  • s contains only printable ASCII characters

Visualization

Tap to expand
INPUTALGORITHMRESULTString: "programming"prograContains duplicate charactersr, m, g appear multiple times1Initialize empty set2For each character:Check if already seen3If new: add to resultMark as seen in set4If duplicate: skipContinue to next characterSet: {p, r, o, g, a, m, i, n}Tracks unique charactersDeduplicated Stringprogam"progamin"Original: 11 charactersResult: 8 unique charactersKey Insight:Using a hash set to track seen characters allows us to removeduplicates in a single pass with O(n) time complexity, muchmore efficient than checking each character against all previous ones.TutorialsPoint - Remove Duplicates from String | Hash Set Approach
Asked in
Google 35 Microsoft 28 Amazon 22 Meta 18
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen