Count and Say
Generate the n-th term of the look-and-say sequence by repeatedly run-length encoding the previous term.
3 min read
strings simulation
Problem#
The look-and-say sequence starts with "1". Each subsequent term describes the previous term by counting runs of consecutive equal digits, e.g., "1211" reads as “one 1, one 2, two 1s” producing "111221". Return the n-th term.
Examples#
n = 1→"1".n = 4→"1211".n = 5→"111221".
Constraints#
1 <= n <= 30.
Hints#
Hint
Iterate from
"1", generating the next term n - 1 times via run-length encoding. Approach#
Start with cur = "1". Repeat n-1 times: scan cur, group consecutive equal characters, and append count + digit to nxt.
Solution#
class Solution {public: string countAndSay(int n) { string cur = "1"; for (int step = 1; step < n; ++step) { string nxt; for (int i = 0; i < (int)cur.size(); ) { int j = i; while (j < (int)cur.size() && cur[j] == cur[i]) ++j; nxt += to_string(j - i); nxt.push_back(cur[i]); i = j; } cur = std::move(nxt); } return cur; }};import "strconv"
func countAndSay(n int) string { cur := "1" for step := 1; step < n; step++ { var nxt []byte for i := 0; i < len(cur); { j := i for j < len(cur) && cur[j] == cur[i] { j++ } nxt = append(nxt, []byte(strconv.Itoa(j-i))...) nxt = append(nxt, cur[i]) i = j } cur = string(nxt) } return cur}class Solution: def countAndSay(self, n: int) -> str: cur = "1" for _ in range(n - 1): parts = [] i = 0 while i < len(cur): j = i while j < len(cur) and cur[j] == cur[i]: j += 1 parts.append(str(j - i)) parts.append(cur[i]) i = j cur = ''.join(parts) return curfunction countAndSay(n) { let cur = "1"; for (let step = 1; step < n; step++) { const parts = []; let i = 0; while (i < cur.length) { let j = i; while (j < cur.length && cur[j] === cur[i]) j++; parts.push(String(j - i)); parts.push(cur[i]); i = j; } cur = parts.join(''); } return cur;}class Solution { public String countAndSay(int n) { String cur = "1"; for (int step = 1; step < n; step++) { StringBuilder nxt = new StringBuilder(); int i = 0; while (i < cur.length()) { int j = i; while (j < cur.length() && cur.charAt(j) == cur.charAt(i)) j++; nxt.append(j - i); nxt.append(cur.charAt(i)); i = j; } cur = nxt.toString(); } return cur; }}function countAndSay(n: number): string { let cur = "1"; for (let step = 1; step < n; step++) { const parts: string[] = []; let i = 0; while (i < cur.length) { let j = i; while (j < cur.length && cur[j] === cur[i]) j++; parts.push(String(j - i)); parts.push(cur[i]); i = j; } cur = parts.join(''); } return cur;}Editorial#
The Conway sequence’s length roughly multiplies by ~1.3 per step; at n = 30 it stays under a few thousand characters — small enough that the naive simulation is fine. Each step is O(L) in current term length.
Complexity#
- Time: O(N * L_max).
- Space: O(L_max).
Concept revision#
Related#