Count and Say

Pattern: String parsing

medium

Each term describes the one before it, run by run, as "how many, then which digit". Start from 1 and build terms one at a time, reading runs of equal digits.

The problem

The count-and-say sequence starts with "1". Each later term is made by reading the previous term aloud in runs of equal digits: for each run, write how many digits it has, then the digit. Given n, return the n-th term. For example, n = 1 gives "1" and n = 4 gives "1211".

The function name countAndSay matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • How do you split "111221" into runs?
  • For each run, what two things do you write?
  • Can the terms be computed directly, or must they be built in order?

Hints

    Brute force, and why it fails

    There is no shortcut formula. Building each term from the one before is the method, and the terms grow by roughly a third each time.

    The key insight

    The rule is a run-length description. Once you can walk the runs of a string, each term is one pass over the previous one.

    Dry run

    10 
    term1

    Term 1 is 1. Read it as one 1, so term 2 is 11.

    Step 1 of 4

    The plan

    s = "1"
    repeat n - 1 times:
        next = empty builder, i = 0
        while i < len(s):
            j = i
            while j < len(s) and s[j] == s[i]: j = j + 1
            append (j - i) then s[i] to next
            i = j
        s = next
    return s
    

    Complexity

    Time
    O(total length of all terms)
    Space
    O(length of the last term)

    Each term is read once to make the next. The length grows by about 30% per term, so the last term dominates.

    Edge cases

    • n = 1: "1".
    • Digits never exceed 3 in this sequence, so each count is one digit.
    • n = 30: the term has several thousand digits, which is fine as a string.
    I've built my logic, show the code

    Java

    class Solution {
        public String countAndSay(int n) {
            String s = "1";
            for (int step = 1; step < n; step++) {
                StringBuilder next = new StringBuilder();
                for (int i = 0; i < s.length(); ) {
                    int j = i;
                    while (j < s.length() && s.charAt(j) == s.charAt(i)) j++;   // s[i..j-1] is one run
                    next.append(j - i).append(s.charAt(i));                     // say "how many" then "which digit"
                    i = j;
                }
                s = next.toString();
            }
            return s;
        }
    }

    C++

    class Solution {
    public:
        string countAndSay(int n) {
            string s = "1";
            for (int step = 1; step < n; step++) {
                string next;
                for (size_t i = 0; i < s.size(); ) {
                    size_t j = i;
                    while (j < s.size() && s[j] == s[i]) j++;      // s[i..j-1] is one run
                    next += to_string(j - i) + s[i];               // say "how many" then "which digit"
                    i = j;
                }
                s = next;
            }
            return s;
        }
    };

    Python

    class Solution:
        def countAndSay(self, n: int) -> str:
            s = "1"
            for _ in range(n - 1):
                out, i = [], 0
                while i < len(s):
                    j = i
                    while j < len(s) and s[j] == s[i]:
                        j += 1                       # s[i..j-1] is one run
                    out.append(str(j - i) + s[i])    # say "how many" then "which digit"
                    i = j
                s = "".join(out)
            return s

    Common mistakes

    • Writing the digit before the count.
    • Building the next term into the same variable that is being read.
    • Starting the loop at the wrong term, which gives the answer for n + 1 or n - 1.

    Similar problems