Count and Say - Problem

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = "1"
  • countAndSay(n) is the run-length encoding of countAndSay(n - 1)

Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters with the concatenation of the count and the character.

For example, to compress the string "3322251":

  • "33" becomes "23" (two 3's)
  • "222" becomes "32" (three 2's)
  • "5" becomes "15" (one 5)
  • "1" becomes "11" (one 1)

Thus the compressed string becomes "23321511".

Given a positive integer n, return the nth element of the count-and-say sequence.

Input & Output

Example 1 — Basic Case
$ Input: n = 1
Output: "1"
💡 Note: Base case: countAndSay(1) is defined as "1"
Example 2 — Second Term
$ Input: n = 4
Output: "1211"
💡 Note: countAndSay(1) = "1", countAndSay(2) = "11" (one 1), countAndSay(3) = "21" (two 1s), countAndSay(4) = "1211" (one 2, one 1)
Example 3 — Longer Sequence
$ Input: n = 5
Output: "111221"
💡 Note: countAndSay(4) = "1211", so countAndSay(5) describes "1211" as "111221" (one 1, one 2, two 1s)

Constraints

  • 1 ≤ n ≤ 30

Visualization

Tap to expand
Count and Say Sequence Evolutionn=1"1"Base casen=2"11"one 1n=3"21"two 1sn=4"1211"one 2, one 1describedescribedescribeRun-Length Encoding Process1. Scan string from left to right2. Count consecutive identical characters3. Append count + character to resultFor n=4, the answer is "1211"
Understanding the Visualization
1
Input
Given n=4, need 4th term of sequence
2
Process
Build each term by describing the previous
3
Output
Return the nth term of the sequence
Key Takeaway
🎯 Key Insight: Each term describes the previous term by counting consecutive identical digits
Asked in
Facebook 45 Google 35
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen