Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Generate the 'look-and-say' sequence starting from '1'.

Problem: Generate the 'look-and-say' sequence starting from '1'.
def nxt(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 = nxt(s)
print(s)
What is printed?
  1. A. 111221
  2. B. 13112221
  3. C. 312221
  4. D. 312211

Correct answer: D. 312211

Terms: 1 → 11 → 21 → 1211 → 111221 → 312211 (three 1s, two 2s, one 1). After 5 steps we are at the 6th term.

More Coding Interview Problems questions

Exams that ask this topic