Algorithmsduplicate character handling
Duplicate Character Handling (Runs, Uniqueness, Maps)
TT
Testlaa Team
May 14, 2026•1 min read
Duplicate handling covers removing repeats, keeping first occurrence only, compressing runs, or counting how many extras exist—often sorting + linear scan or hash map of last index.
Why this shows up in the real world
URL slug generators strip duplicate hyphens. Log deduplication collapses repeated error lines for alerting noise reduction.
Core idea (explained for students)
Remove adjacent duplicates in one pass: compare s[i] with out[-1] while building a list. For “remove all instances of dup beyond k,” track counts per character.
Try this in Python
def remove_adjacent_dupes(s: str) -> str:
out: list[str] = []
for ch in s:
if not out or out[-1] != ch:
out.append(ch)
return "".join(out)
print(remove_adjacent_dupes("aaabbbcca"))
Common mistakes
- Non-adjacent duplicates need different logic than run compression.
- Mutating a string in a loop with
s[i] =—strings are immutable; build new sequences.
Key takeaways
- Separate adjacent duplicate removal from global uniqueness problems.
''.joinonce at the end beats repeated concatenation.
Tags:
StringsPythonStudents
