Maintained by Vikas Dulgunde, software engineer
The sequence starts at "1". Every term after the first is created by scanning the previous term from left to right and describing what you read. You count how many times each digit repeats in a row, then write that count followed by the digit itself.
Take "21" as an example. Reading left to right you see one 2 followed by one 1, so you say "one 2, one 1", which you write down as "1211". That string becomes the next term, and you repeat the same reading process to get the one after it.
Your job is to return the term at position n. You are given only the integer n, and you generate every term from the first up to the nth by applying the read-and-describe rule one step at a time.
Each term only ever contains the digits 1, 2, and 3, because no digit can appear more than three times in a row once you follow the rule. The strings still grow quickly, so the work is in producing each term correctly rather than in any tricky math.
The first term is defined as the string "1". There is nothing to read or transform.
Term 1 is "1", read as one 1 gives "11". "11" read as two 1s gives "21". "21" read as one 2 then one 1 gives "1211".
Term 5 is "111221". Reading it: three 1s, then two 2s, then one 1, which writes as "31" + "22" + "11" = "312211".
Visible test cases
There is no shortcut formula. You must build term 1, then term 2, and so on up to term n, because each term depends entirely on the one before it.
To turn one term into the next, walk through it once and find runs of the same digit. For each run, append the run length followed by the digit.
Use an inner pointer that skips past a whole run at a time instead of advancing one character per step, so each character is visited only once per term.
Start from "1" and apply the read-and-describe step n minus 1 times. Each step is a single left-to-right pass that groups consecutive equal digits and writes count plus digit.
Express the term directly from its definition: term n is the run-length encoding of term n minus 1, with term 1 as the base case.