← Back to libraryQuestion 60 of 273
⌨️Java CodingIntermediate

Remove Duplicate Characters from a String

📌 Definition:

Given "programming", produce "progamin" — keep the first occurrence of each character and drop later duplicates.

📖 Detailed Explanation:

Iterate once, appending a character only if it has not been seen, tracking membership in an ordered set. O(n). Using an unordered set or sorting loses the original order.

💻 Solutions:
public static String removeDuplicates(String s) {
    Set<Character> seen = new LinkedHashSet<>();
    for (char c : s.toCharArray()) seen.add(c);
    StringBuilder sb = new StringBuilder();
    for (char c : seen) sb.append(c);
    return sb.toString();
}
function removeDuplicates(s) {
  return [...new Set(s)].join('');
}
def remove_duplicates(s):
    return ''.join(dict.fromkeys(s))
🔑 Key Points:
  • Track seen chars in a set
  • Ordered set preserves first-seen order
  • Append only unseen characters
  • O(n) time, O(k) space
🌍 Real-World Example:

De-duplicating while preserving order is exactly what you do cleaning a list of inputs or building unique, ordered column headers.

🎯 Scenario-Based Interview Question:

A candidate uses a plain HashSet and the output order is scrambled. Fix?