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- A. 3
- B. 6
- C. 5
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- A binary string s = "1100101" is to be made alternating. Two targets are possible: "0101010..." and "1010101...", each the same length as…
- Count how many copies of the word BALLOON can be formed from the letters of "lloolldnaubbalo" (each letter used at most once per copy)…
- Children have ratings r = [1, 0, 2, 2, 1]. Each child gets at least one candy, and a child with a higher rating than a neighbour gets more…
- Let x = 0. For i from 1 to 10: if i mod 3 == 0 then x = x + i, otherwise x = x - 1. What is printed? x = 0 for i = 1 to 10 if i mod 3 == 0…
- A rope of length L is cut into two parts of lengths floor(L/2) and L - floor(L/2) whenever its length is 2 or more; the cost of a cut is…
- Jobs each take one unit of time and carry a deadline: 1, 1, 2, 3, 4, 4 (the last slot the job may use; slots are 1, 2, 3, ...). The…