Count and Say

Build each term of the count-and-say sequence by reading the previous term aloud, run by run.

The count-and-say sequence is a list of digit strings that starts with "1". Each later term describes the term before it, read aloud: for every stretch of equal digits, say how many there are, then the digit. Given a number n, return term number n as a string.

Example 1
Input: n = 1
Output: "1"
Example 2
Input: n = 4
Output: "1211"
Explanation: "1" is one 1, so term 2 is "11". That is two 1s, so term 3 is "21". That is one 2 and one 1, so term 4 is "1211".
Solution

The Idea

Try reading a number out loud the way people sometimes read a long code over the phone: "two 1s" instead of "one, one". Count-and-say does exactly that, and then writes down what it said as digits. "Two 1s" becomes "21".

Follow Example 2 one term further. Term 4 is "1211". Read aloud, it is one 1, one 2, two 1s, so term 5 is "111221". Now read term 5 aloud: three 1s, two 2s, one 1. Written down, that is "31", "22" and "11", so term 6 is "312211".

So how do you read a term aloud, step by step? You look for stretches of the same digit standing side by side. Such a stretch is called a run. In "111221" the runs are "111", "22" and "1", and each one is said as its length followed by its digit. Look at the picture below.

Term 5, 111221, splits into three runs: three 1s, two 2s and one 1. Each run is read aloud as count then digit: 31, 22, 11. Joined, they give term 6, 312211.

The top row is term 5, with its digits grouped into the three runs. The orange run, labelled "run: three 1s", is read aloud as "31", and the other two runs give "22" and "11". Put side by side, the three pieces make term 6, "312211".

So one term follows from the term before it and nothing else. To get term n, start at "1" and read aloud n - 1 times, each time turning a term into the next one, run by run.

Solution Approach

Turning that idea into code means settling three things: how to get from "1" to term n, how to find where each run ends, and how to write the new term without slow copying.

Building the terms in order

Is there a shortcut straight to term n? There is no simple formula for it, because each term is made only by reading the one before. So a loop starts with "1" and replaces it with the next term n - 1 times. Only the current term needs to be kept.

Finding each run

Where does a run end? Put a marker i on the first digit of the run, and a second marker j on the same spot. Move j forward while it sees the same digit as i. The picture shows both markers above term 5: i on the first 1, and j stopped on the first 2, so the run covers the three 1s and its length is j - i, which is 3.

The next run starts right where j stopped, so i jumps there and the search repeats. This way every digit is looked at once, and the last run ends when j reaches the end of the string, with no special case.

Writing the next term

How do the pieces get joined? Adding to a Java String with + inside a loop makes a new string each time and copies everything written so far. A StringBuilder is a growable buffer of characters, so appending the count and the digit to it does not copy the earlier pieces.

Can a count ever need two digits, such as a run of twelve 1s? Not in this sequence. Running the code for the first 40 terms shows that no digit above 3 ever appears, so every count is a single digit.

Java Solution

The method countAndSay and its helper say work in these steps:

  1. First, countAndSay sets term to "1". A loop with counter k runs from 2 to n and replaces term with say(term), so after each round term holds term number k.
  2. Inside say, an empty StringBuilder called sb will collect the next term, and the marker i starts at position 0, the first digit of the first run.
  3. An outer loop handles one run per round. It sets j to i, and an inner loop moves j forward while the digit at j equals the digit at i.
  4. The run is now the digits from i up to just before j. Append its length, j - i, and then its digit to sb, and move i to j, the start of the next run.
  5. When i reaches the end of the string, say returns the contents of sb, and once the loop over k is done, countAndSay returns term.

The main method prints terms 1 to 6, reads aloud a string that contains a 3 and a 5, and prints how long term 30 is.

Java
public class CountAndSay {

    public static String countAndSay(int n) {
        String term = "1";
        for (int k = 2; k <= n; k++) {
            term = say(term);                 // term now holds term number k
        }
        return term;
    }

    // Read a term aloud: each run of equal digits becomes "count digit"
    static String say(String s) {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            int j = i;
            while (j < s.length() && s.charAt(j) == s.charAt(i)) {
                j++;                          // s[i..j-1] is one run
            }
            sb.append(j - i).append(s.charAt(i));
            i = j;                            // the next run starts at j
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        for (int n = 1; n <= 6; n++) {
            System.out.println("n = " + n + ": " + countAndSay(n));
        }
        System.out.println("say(\"3322251\") = " + say("3322251"));
        System.out.println("n = 30 has " + countAndSay(30).length() + " digits");
    }
}

Running it prints:

Output
n = 1: 1
n = 2: 11
n = 3: 21
n = 4: 1211
n = 5: 111221
n = 6: 312211
say("3322251") = 23321511
n = 30 has 4462 digits

For n = 1 the loop over k never runs, so "1" comes back unchanged. The line for n = 6 shows 312211, the same term 6 as at the bottom of the picture.

The line for say("3322251") reads two 3s, three 2s, one 5 and one 1, which gives 23321511. So say works for any digits, not only the 1s and 2s of the early terms.

The last line shows how fast the terms grow: term 30 already has 4462 digits. There is also a real trap in finding runs. A version that compares each digit with the one before, and writes a run only when the digit changes, never writes the last run. Run on "1" it returns an empty string, and on "1211" it returns "1112". The inner loop above has no such gap, because a run also ends when j reaches the end of the string.

Complexity

The work is one pass of say over each term, from term 1 up to term n - 1.

  • Time: O(L), where L is the length of term n. Each call to say looks at every digit of its term once. Past the first few terms, each term is about 30% longer than the one before, so all the earlier terms together are only a few times the length of the last one.
  • Space: O(L). At any moment only the current term and the StringBuilder holding the next one exist, and neither is longer than term n.

Grouping a string into runs is also the first step of Count Binary Substrings.