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

String Compression

Encode adjacent character runs as character-count pairs. Students reset a run counter, flush completed runs, and include the final run after traversal.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 12 of 14
string-compression.py
1# Take string
2s = input("Enter string: ")
3
4# Compress
5if not s:
6 compressed = ""
7else:
8 compressed = ""
9 count = 1
10 for i in range(1, len(s)):
11 if s[i] == s[i-1]:
12 count += 1
13 else:
14 compressed += s[i-1] + str(count)
15 count = 1
16 compressed += s[-1] + str(count)
17
18print(f"Compressed: {compressed}")

Output

Enter string: aaabbcc
Compressed: a3b2c2

In this one

  • Count adjacent runs
  • Reset on character changes
  • Flush the final run

How it works

  1. 1

    Start a nonempty run count at one.

  2. 2

    Append a completed character-count pair on each change.

  3. 3

    Append the last run after traversal.

Edge cases

Why append after the loop?

Why append after the loop?

The final run has no later different character to trigger a flush.

Does compression always reduce length?

Does compression always reduce length?

No. Short runs can make the encoded string longer.

What's going on

Equal neighboring characters increase count. A change appends the previous character and its count, then begins a new run at one.

After the loop, the last run is appended explicitly. aaabb becomes a3b2. This run-length encoding is not guaranteed to shorten text: abc becomes a1b1c1. Empty input is handled separately, avoiding access to s[-1] when no character exists.

Why append after the loop? The final run has no later different character to trigger a flush.

Does compression always reduce length? No. Short runs can make the encoded string longer.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does aaa become?

Pick an answer to check it.

Question 2

Why append after the loop?

Pick an answer to check it.

Questions people ask

Why append after the loop?

The final run has no later different character to trigger a flush.

Does compression always reduce length?

No. Short runs can make the encoded string longer.

What does aaa become?

a3.