Coding Challenge Practice - Question 69

Published: (December 2, 2025 at 05:57 PM EST)
2 min read
Source: Dev.to

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

  1. Base case – if n is 1, return "1".
  2. Iterate from the second term up to n:
    • Scan the current term (result) character by character.
    • Keep a count of how many times the same digit appears consecutively.
    • When the digit changes (or the end of the string is reached), append count and the digit to a new string current, then reset count.
    • After processing the whole term, set result to current.
  3. After completing the loop, result holds 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;
}
Back to Blog

Related posts

Read more »

Challenge no. 1 - User Avatar

Communities DEV Community !DEV Community Logohttps://media2.dev.to/dynamic/image/width=65,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-...