ProgrammingModerateInfosys · Cognizant

The string s = "aaabbbcc" is cut down so that no two adjacent letters are equal, by deleting characters. The greedy keeps a character when it differs from the last kept character and deletes it otherwise. What is the number of characters deleted (printed)?

The string s = "aaabbbcc" is cut down so that no two adjacent letters are equal, by deleting characters. The greedy keeps a character when it differs from the last kept character and deletes it otherwise. What is the number of characters deleted (printed)?
prev = none; deleted = 0
for each character ch in s
    if ch == prev then deleted = deleted + 1
    else prev = ch
end for
Print deleted
  1. A. 3
  2. B. 6
  3. C. 5
  4. D. 8

Correct answer: C. 5

Each run of equal letters keeps one character, and the three runs are a, b and c, so five characters are deleted. Counting distinct letters, the length minus one, and the length of the string each give a different number.

More Pseudocode and Code Tracing questions

Exams that ask this topic