Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …).

Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …).
def say(s):
    out, i = [], 0
    while i < len(s):
        j = i
        while j < len(s) and s[j] == s[i]: j += 1
        out.append(str(j - i) + s[i]); i = j
    return "".join(out)
s = "1"
for _ in range(5): s = say(s)
print(s, say("3322251"))
What is printed?
  1. A. 312211 2332251
  2. B. 312211 23321511
  3. C. 111221 23321511
  4. D. 13112221 23321511

Correct answer: B. 312211 23321511

Terms: 1 → 11 → 21 → 1211 → 111221 → 312211 (five steps). "3322251" = two 3s, three 2s, one 5, one 1 → "23" "32" "15" "11". Each step is linear in the term length; terms grow by about 30% per step.

More Coding Interview Problems questions

Exams that ask this topic