Count and Say

Generate the n-th term of the look-and-say sequence by repeatedly run-length encoding the previous term.

Medium
Time O(N * L) Space O(L)
LeetCode
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#

Count and Say
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.