Data Structures & AlgorithmsModerateTCS NQT · string round

Problem: What does this run-length encoder print for 'aaabccdd'?

Problem: What does this run-length encoder print for 'aaabccdd'?
s = 'aaabccdd'
out = []
i = 0
while i < len(s):
    j = i
    while j < len(s) and s[j] == s[i]:
        j += 1
    out.append(s[i] + str(j - i))
    i = j
print(''.join(out))
What is printed?
  1. A. a3b1c2d
  2. B. a3bc2d2
  3. C. a3b1c2d2
  4. D. aaabccdd

Correct answer: C. a3b1c2d2

Runs are a x3, b x1, c x2 and d x2, and each run is written as its letter followed by its length. Printing the input unchanged is the trap for a bad encoder.

More Coding Interview Problems questions

Exams that ask this topic