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 nn
Example 1
Output: "1"
Example 2
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".
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.
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 nn - 1
Solution Approach
Turning that idea into code means settling three things: how to get from "1" to term n
Building the terms in order
Is there a shortcut straight to term nn - 1
Finding each run
Where does a run end? Put a marker ijjiijj - i
The next run starts right where jij
Writing the next term
How do the pieces get joined? Adding to a Java String+StringBuilder
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 countAndSaysay
- First,
setscountAndSay to "1". A loop with counterterm runs from 2 tok and replacesn withterm , so after each roundsay(term) holds term numberterm .k - Inside
, an emptysay calledStringBuilder will collect the next term, and the markersb starts at position 0, the first digit of the first run.i - An outer loop handles one run per round. It sets
toj , and an inner loop movesi forward while the digit atj equals the digit atj .i - The run is now the digits from
up to just beforei . Append its length,j , and then its digit toj - i , and movesb toi , the start of the next run.j - When
reaches the end of the string,i returns the contents ofsay , and once the loop oversb is done,k returnscountAndSay .term
The main
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:
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 = 1kn = 6
The line for say("3322251")say
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
Complexity
The work is one pass of sayn - 1
- Time: O(L), where L is the length of term
. Each call ton 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.say - Space: O(L). At any moment only the current term and the
holding the next one exist, and neither is longer than termStringBuilder .n
Grouping a string into runs is also the first step of