Look-and-Say Sequence

medium Series and Sequences

Problem

The look-and-say sequence starts with 1. Each next term describes the previous term: 1 is 'one 1' so the next term is 11. 11 is 'two 1s' so the next term is 21. 21 is 'one 2, one 1' so the next term is 1211. Read n and print the first n terms, one on each line.

Constraints

  • 0 <= n <= 20

Examples

Input

5

Output

1
11
21
1211
111221

Solutions

Best approachTime O(L) per termSpace O(L)

To build the next term we scan the current term and count runs of equal digits. For each run we write the length and the digit. The terms are text, not numbers, because they grow very long.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Print the first n terms of the look-and-say sequence.
 * Input   : One integer n.
 * Output  : n lines, one term per line.
 * Approach: Read the previous term aloud: count equal digits in a row.
 * Time    : O(L) per term
 * Space   : O(L)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method receives one term and returns the next term. Example: "21" -> "1211".
    static String nextTerm(String term) {
        StringBuilder next = new StringBuilder();
        int index = 0;

        // Step 1: Go through the term from left to right.
        while (index < term.length()) {
            // Step 2: Count how many times the same digit repeats in a row. This is called a "run".
            char digit = term.charAt(index);
            int runLength = 0;
            while (index < term.length() && term.charAt(index) == digit) {
                runLength++;
                index++;
            }

            // Step 3: Write the count and then the digit. Example: three 2s -> "32".
            next.append(runLength).append(digit);
        }
        return next.toString();
    }

    public static void main(String[] args) {
        int n = new Scanner(System.in).nextInt();

        // Step 4: Start with the first term "1". Print each term and then calculate the next one.
        String term = "1";
        for (int line = 1; line <= n; line++) {
            System.out.println(term);
            term = nextTerm(term);
        }
    }
}
Hints (2)
  1. Read the term aloud: 'one 1', 'two 1s', ...
  2. Use an inner loop to count a run of equal digits.