38. Count and Say
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to generate the nth term of the "count-and-say" sequence. This sequence starts with "1". Each subsequent term is generated by describing the previous term. For instance, "1" is read as "one 1", which gives "11". "11" is read as "two 1s", giving "21". The core task is to implement this generation process, which is a form of run-length encoding, for n-1 steps starting from the initial term "1".
Solution
Count and Say in Python
class Solution:
def countAndSay(self, n: int) -> str:
# Base case: if n is 1, return "1".
if n == 1:
return "1"
# Start with the first term of the sequence.
s = "1"
# Iterate from the 2nd term up to the nth term.
for _ in range(2, n + 1):
# Use a list to store parts of the next string for efficiency.
next_s_parts = []
i = 0
# Use a pointer 'i' to scan through the current string.
while i < len(s):
# 'j' helps to find the end of a group of identical consecutive characters.
j = i
while j < len(s) and s[j] == s[i]:
j += 1
# The count of the character group is (j - i).
# The character is s[i].
count = j - i
next_s_parts.append(str(count))
next_s_parts.append(s[i])
# Move the main pointer 'i' to the start of the next group.
i = j
# Join the parts to form the next string.
s = "".join(next_s_parts)
return s
Count and Say in Java
class Solution {
public String countAndSay(int n) {
// Base case: if n is 1, return "1".
if (n == 1) {
return "1";
}
// Start with the first term of the sequence.
String currentS = "1";
// Iterate from the 2nd term up to the nth term.
for (int i = 2; i <= n; i++) {
// Use StringBuilder for efficient string construction.
StringBuilder nextSBuilder = new StringBuilder();
int len = currentS.length();
// Use a pointer 'j' to scan through the current string.
for (int j = 0; j < len; ) {
// 'k' helps to find the end of a group of identical consecutive characters.
int k = j;
while (k < len && currentS.charAt(k) == currentS.charAt(j)) {
k++;
}
// The count of the character group is (k - j).
// The character is currentS.charAt(j).
nextSBuilder.append(k - j);
nextSBuilder.append(currentS.charAt(j));
// Move the main pointer 'j' to the start of the next group.
j = k;
}
// Update the current string for the next iteration.
currentS = nextSBuilder.toString();
}
return currentS;
}
}
Count and Say in C++
class Solution {
public:
string countAndSay(int n) {
// Base case: if n is 1, return "1".
if (n == 1) {
return "1";
}
// Start with the first term of the sequence.
string current_s = "1";
// Iterate from the 2nd term up to the nth term.
for (int i = 2; i <= n; ++i) {
string next_s = "";
int len = current_s.length();
// Use a pointer 'j' to scan through the current string.
for (int j = 0; j < len; ) {
// 'k' helps to find the end of a group of identical consecutive characters.
int k = j;
while (k < len && current_s[k] == current_s[j]) {
k++;
}
// The count of the character group is (k - j).
// The character is current_s[j].
next_s += to_string(k - j);
next_s += current_s[j];
// Move the main pointer 'j' to the start of the next group.
j = k;
}
// Update the current string for the next iteration.
current_s = next_s;
}
return current_s;
}
};
Count and Say in TypeScript
function countAndSay(n: number): string {
// Base case: if n is 1, return "1".
if (n === 1) {
return "1";
}
// Start with the first term of the sequence.
let currentS = "1";
// Iterate from the 2nd term up to the nth term.
for (let i = 2; i <= n; i++) {
// Use an array to store parts of the next string for efficiency.
const nextSParts: string[] = [];
let j = 0;
// Use a pointer 'j' to scan through the current string.
while (j < currentS.length) {
// 'k' helps to find the end of a group of identical consecutive characters.
let k = j;
while (k < currentS.length && currentS[k] === currentS[j]) {
k++;
}
// The count of the character group is (k - j).
// The character is currentS[j].
const count = k - j;
nextSParts.push(String(count));
nextSParts.push(currentS[j]);
// Move the main pointer 'j' to the start of the next group.
j = k;
}
// Join the parts to form the next string.
currentS = nextSParts.join('');
}
return currentS;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.