Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Remove Adjacent Duplicates

Collapse adjacent duplicate characters with Python. Students track the previous character, keep separated repeats, and distinguish runs from global duplicates.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 7 of 14
remove-adjacent-duplicates.py
1# Take string input
2s = input("Enter a string: ")
3
4# Remove adjacent duplicates
5result = ""
6prev_char = None
7for char in s:
8 if char != prev_char:
9 result += char
10 prev_char = char
11
12print(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. 1

    Initialize result empty and prev_char None.

  2. 2

    Append char when different from prev_char.

  3. 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.