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 - StringBuilder Approach INPUT n = 1 (positive integer) Count-and-Say Sequence: n=1 n=2 n=3 ... "1" "11" "21" Run-Length Encoding: Count consecutive chars then append count + char "1" --> "one 1" --> "11" "11" --> "two 1s" --> "21" ALGORITHM STEPS 1 Base Case Check If n=1, return "1" 2 Get Previous Result Recursive: countAndSay(n-1) 3 Build New String Use StringBuilder for RLE 4 Return Result Convert to string StringBuilder sb = new StringBuilder(); // Count consecutive // Append count + char return sb.toString(); FINAL RESULT For n = 1: "1" Base case returns "1" Output: "1" Example sequence: n=1: "1" n=2: "11" (one 1) n=3: "21" (two 1s) n=4: "1211" (one 2, one 1) Key Insight: StringBuilder is efficient for string concatenation in loops. Each term describes the previous term using run-length encoding. Time complexity is O(n * m) where m is the max string length at step n. TutorialsPoint - Count and Say | StringBuilder Approach
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