Data Structures & AlgorithmsModerateFlipkart/Uber OA · placement

Run-length encoding: each maximal run is written as the character followed by its length. What is printed?

Run-length encoding: each maximal run is written as the character followed by its length. What is printed?
s = "yyyyyyyyxx"
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
enc = "".join(out)
print(enc, len(enc) < len(s))
  1. A. y8x2 True
  2. B. y2y2y2y2x2 False
  3. C. y8x4 True
  4. D. y8x3 True

Correct answer: A. y8x2 True

Runs are maximal, so equal neighbouring characters merge into one group; the encoding only helps when runs are long. Output: y8x2 True.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic