Conway's Sequence

Level: Beginner 15–30 min

Concepts: AlgorithmsStringsIncremental Design


Generate terms of the look-and-say sequence (also known as Conway’s sequence). Each term is produced by describing the digits of the previous term.

How It Works

Start with "1". To get the next term, read the current term aloud:

  • "1" → one 1 → "11"
  • "11" → two 1s → "21"
  • "21" → one 2, one 1 → "1211"
  • "1211" → one 1, one 2, two 1s → "111221"
  • "111221" → three 1s, two 2s, one 1 → "312211"

Requirements

Write a function that given a starting string and a number of iterations, returns the resulting term.

  • lookAndSay("1", 1)"11"
  • lookAndSay("1", 2)"21"
  • lookAndSay("1", 5)"312211"

Also support generating a single next term:

  • nextTerm("1")"11"
  • nextTerm("111221")"312211"

Test Cases

InputIterationsResult
"1"0"1"
"1"1"11"
"1"2"21"
"1"3"1211"
"1"4"111221"
"1"5"312211"
"2"1"12"
"2"2"1112"
"22"1"22"
"1211"1"111221"
"3211"1"13112111"

Edge cases:

  • Zero iterations returns the input unchanged
  • Single digit input
  • Input with runs longer than 9 (e.g. ten 1s → "101" — decide how to handle)

Bonus

  • Start from different seeds (not just "1") and observe how sequences evolve
  • Calculate the length of the nth term without generating it (lengths grow by roughly 30% each iteration — look up Conway’s constant λ ≈ 1.303577)
  • Support multi-character “digits” (e.g. atoms in Conway’s cosmological theorem)

Hint

Start with nextTerm for a single-character input. Then handle two identical characters. Then mixed characters. The multi-iteration version is just applying nextTerm repeatedly — get the single step right first.