algoadvance

Leetcode 38. Count and Say

Problem Statement

The Count and Say sequence is a sequence of digit strings defined by the recursive formula:

To determine how you “say” a digit string, you split it into the minimal number of groups so that each group is a contiguous section all of the same digit. Then for each group, say the number of digits, followed by the digit. You concatenate these descriptions to form the next term.

For example:

"1" is read off as "one 1" → "11".
"11" is read off as "two 1s" → "21".
"21" is read off as "one 2, then one 1" → "1211".
"1211" is read off as "one 1, one 2, then two 1s" → "111221".

Given a positive integer n, return the n-th term of the count-and-say sequence.

Clarifying Questions

  1. Input Range:
    • What is the range of n?
      • Typically 1 ≤ n ≤ 30, but we should ensure sequences are properly handled within this range.
  2. Output Format:
    • Should the output be a string?
      • Yes, as per the problem statement, the output will be a string representation of the sequence.

Strategy

  1. Iterative Simulation:
    • We start from countAndSay(1) = "1".
    • For each increment in n, we generate the next sequence by “saying” the current sequence.
  2. Generate Next Sequence:
    • Traverse the current sequence and count the occurrences of each digit until the digit changes.
    • Use the counts and digits to form the next sequence.

Code

public class CountAndSay {
    public String countAndSay(int n) {
        String result = "1";
        for (int i = 1; i < n; i++) {
            result = getNextSequence(result);
        }
        return result;
    }

    private String getNextSequence(String s) {
        StringBuilder nextSeq = new StringBuilder();
        int i = 0;
        while (i < s.length()) {
            char digit = s.charAt(i);
            int count = 0;
            // Count the number of occurrences of the same digit
            while (i < s.length() && s.charAt(i) == digit) {
                i++;
                count++;
            }
            // Append the count and the digit to the next sequence
            nextSeq.append(count).append(digit);
        }
        return nextSeq.toString();
    }

    public static void main(String[] args) {
        CountAndSay sol = new CountAndSay();
        int n = 5; // Example input
        System.out.println(sol.countAndSay(n)); // Output: "111221"
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI