Remove Adjacent Duplicates
Collapse adjacent duplicate characters with Python. Students track the previous character, keep separated repeats, and distinguish runs from global duplicates.
1# Take string input2s = input("Enter a string: ")34# Remove adjacent duplicates5result = ""6prev_char = None7for char in s:8 if char != prev_char:9 result += char10 prev_char = char1112print(f"Result: {result}")
Output
Enter a string: aabbcc Result: abc
In this one
- Track the previous accepted character
- Collapse runs
- Preserve nonadjacent repeats
How it works
- 1
Initialize result empty and prev_char None.
- 2
Append char when different from prev_char.
- 3
Update the tracker on acceptance and print result.
Edge cases
Does banana change?
Does banana change?
No. Equal letters are separated, not adjacent.
What happens for empty input?
What happens for empty input?
The result remains empty.
What's going on
A character is appended only when it differs from prev_char. The tracker then records the newly accepted character.
For aaabbba, the result is aba: the final a survives because it is not adjacent to another a in that run. This does not repeatedly delete equal pairs; it keeps one copy per run. None initially ensures the first character is accepted.
Does banana change? No. Equal letters are separated, not adjacent.
What happens for empty input? The result remains empty.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does aaabb become?
Pick an answer to check it.
Question 2
Does banana change?
Pick an answer to check it.
Questions people ask
Does banana change?
No. Equal letters are separated, not adjacent.
What happens for empty input?
The result remains empty.
What does aaabb become?
ab.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum