Data Structures & AlgorithmsModerateTCS NQT Digital · greedy strings

Problem: Minimum number of deletions so that no two adjacent characters of 'aaabbb' are equal. Run the code.

Problem: Minimum number of deletions so that no two adjacent characters of 'aaabbb' are equal. Run the code.
s = 'aaabbb'
kept = []
for c in s:
    if not kept or kept[-1] != c:
        kept.append(c)
print(len(s) - len(kept))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 2
  4. D. 5

Correct answer: A. 4

The greedy keeps one character from each run, so 'ab' remains and 4 characters are deleted.

More Coding Interview Problems questions

Exams that ask this topic