14. Look and Say Pattern
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given an integer n, return the nth term in the Look-and-Say Sequence, also known as the Count and Say sequence.
This sequence is built by describing the previous term in terms of the count of digits in groups of the same digit.
🔁 How It Works:
Start with "1" as the first term. To generate each subsequent term:
Read off the digits of the previous term.
For each group of consecutive identical digits, state:
The number of times it appears (the count),
Followed by the digit itself.
📚 Examples of the Sequence:
1 # First term
11 # One 1 → "11"
21 # Two 1s → "21"
1211 # One 2, One 1 → "1211"
111221 # One 1, One 2, Two 1s → "111221"
...📘 Examples
Example 1:
Input: n = 5
Output: 111221
Explanation: The sequence evolves as: 1 → 11 → 21 → 1211 → 111221
Example 2:
Input: n = 3
Output: 21
Explanation: The third term is: 1 → 11 → 21
🔒 Constraints
$1 \leq n \leq 30$
✅ My Approach
🧠 Iterative Character Grouping
We iteratively build each term in the Look-and-Say sequence by scanning the previous term and counting consecutive digits.
🔹 Algorithm Steps:
Initialize the sequence with the first term as
"1".Repeat the following process from the 2nd term to the
nth term:Create an empty string
next_term.Traverse the current term:
Count how many times a digit repeats consecutively.
Append the count followed by the digit to
next_term.
Update the current term to
next_termfor the next iteration.
Return the final term after
n - 1transformations.
🧮 Time and Auxiliary Space Complexity
Time
O(n × L), where L is the average length of terms in the sequence. Each of the n iterations processes a string with increasing size.
Auxiliary Space
O(L), used for building the next term at each step.
🧠 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated