public class CountAndSay { public static String countAndSay(int n) { if (n == 1) return "1"; String prev = countAndSay(n - 1); StringBuilder result = new StringBuilder(); int count = 1; for (int i = 1; i < prev.length(); i++) { if (prev.charAt(i) == prev.charAt(i - 1)) { count++; } else { result.append(count).append(prev.charAt(i - 1)); count = 1; } } result.append(count).append(prev.charAt(prev.length() - 1)); return result.toString(); } public static void main(String[] args) { System.out.println(countAndSay(4)); } }
The Count and Say sequence starts with "1" for n=1.
For n=2, it reads "1" as "one 1" → "11".
For n=3, it reads "11" as "two 1s" → "21".
For n=4, it reads "21" as "one 2, then one 1" → "1211".
public class CountAndSay { public static String countAndSay(int n) { if (n == 1) return "1"; String prev = countAndSay(n - 1); StringBuilder result = new StringBuilder(); int count = 1; for (int i = 1; i < prev.length(); i++) { if (prev.charAt(i) == prev.charAt(i - 1)) { count++; } else { result.append(count).append(prev.charAt(i - 1)); count = 1; } } result.append(count).append(prev.charAt(prev.length() - 1)); return result.toString(); } public static void main(String[] args) { System.out.println(countAndSay(5)); } }
Sequence steps:
- n=1: "1"
- n=2: "11" (one 1)
- n=3: "21" (two 1s)
- n=4: "1211" (one 2, one 1)
- n=5: "111221" (one 1, one 2, two 1s)
public class CountAndSay { public static String countAndSay(int n) { if (n == 1) return "1"; String prev = countAndSay(n - 1); StringBuilder result = new StringBuilder(); int count = 1; for (int i = 0; i < prev.length(); i++) { if (prev.charAt(i) == prev.charAt(i - 1)) { count++; } else { result.append(count).append(prev.charAt(i - 1)); count = 1; } } result.append(count).append(prev.charAt(prev.length() - 1)); return result.toString(); } }
The loop starts at i=0 and tries to access prev.charAt(i - 1) which is prev.charAt(-1) at first iteration.
This causes StringIndexOutOfBoundsException.
The length of the sequence roughly doubles each step, so length at step n is about 2^n.
Each recursive call processes the previous string, so total work is about n times 2^n.
Recursion for large n causes stack overflow and repeated calls.
There is no direct formula for nth term.
Parallel threads cannot compute terms independently because each depends on the previous.
Iterative approach builds terms one by one efficiently.
