Coding Challenge Practice - Question 69
Source: Dev.to
Problem Description
Create a function that returns the n-th term of the “look‑and‑say” sequence as a string.
The sequence starts with "1" (for n = 1). Each subsequent term describes the digits of the previous term: count consecutive identical digits and then write the count followed by the digit.
Solution Explanation
- Base case – if
nis 1, return"1". - Iterate from the second term up to
n:- Scan the current term (
result) character by character. - Keep a
countof how many times the same digit appears consecutively. - When the digit changes (or the end of the string is reached), append
countand the digit to a new stringcurrent, then resetcount. - After processing the whole term, set
resulttocurrent.
- Scan the current term (
- After completing the loop,
resultholds the n-th term, which is returned.
The algorithm runs in O(k) time per iteration, where k is the length of the current term, and uses O(k) additional space for the temporary string.
Code
function getNthNum(n) {
// Base case
if (n === 1) return "1";
let result = "1";
// Build each term up to n
for (let i = 2; i <= n; i++) {
let current = "";
let count = 1;
// Describe the previous term
for (let j = 1; j <= result.length; j++) {
if (result[j] === result[j - 1]) {
count++;
} else {
current += count.toString() + result[j - 1];
count = 1;
}
}
result = current;
}
return result;
}