Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1).

Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1).
def compress(s):
    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) if j - i > 1 else ''))
        i = j
    return ''.join(out)
print(compress("aaabccddddddddddde"))
What is printed?
  1. A. a3bc2d11e
  2. B. a3b1c2d11e1
  3. C. a3bc2d1e
  4. D. a3bc2d10e

Correct answer: A. a3bc2d11e

Runs: aaa → a3, b → b, cc → c2, eleven d's → d11, e → e. The run length can exceed 9, so it must be written with str(), not as a single digit character (which gives the d1 trap). O(n).

More Coding Interview Problems questions

Exams that ask this topic