Start from the string "1". To get the next term, read the current one aloud from left to right, one block of identical digits at a time: say how many there are, then which digit it is. Write down what you said, and that is the next term.
For example, "4441223" is read as "three 4s, one 1, two 2s, one 3", which is written "34112213".
Building every term from the one before gives the sequence "1", "11", "21", "1211", … Given n, return term number n, counting the starting "1" as term 1.
Term 4 is "1211": one 1, one 2, two 1s. Saying that gives "11" + "12" + "21".
Term 2 is "11", which is a single block of two 1s.
Term 6 is "312211": one 3, one 1, two 2s, two 1s.
Constraints
1 <= n <= 30Every term holds only the digits 1, 2 and 3, and term 30 is under 5,000 characters long.
There is no shortcut to term n: start from "1" and build each term from the one before it, n - 1 times.
There's no formula that jumps to term n. Each term is defined only by reading the one before it, so the way to get term n is to start at "1" and build every term in between, n - 1 times.
Time O(L)Space O(L)
The full walkthrough and code are part of Premium
5