There is one endless string of the digits 1 and 2 that describes itself. Split it into groups of equal neighbouring digits and write down the size of each group, in order. The sizes you get spell out the string itself. It starts 1221121, which splits into the groups 1 | 22 | 11 | 2 | 1, of sizes 1, 2, 2, 1, 1: its own first five digits.
Given n, return how many 1s appear among the first n digits of this string.
Example 1
Input: n = 7 Output: 4 Why: the first 7 digits are 1221121
2 more examples and the constraints
Example 2
Input: n = 1 Output: 1 Why: the string starts with a 1
Example 3
Input: n = 10 Output: 5 Why: the first 10 digits are 1221121221
Constraints
- 1 ≤ n ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Rebuild in roundsO(n)
- Two pointers, one passO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 100,000 | Verdict |
|---|---|---|---|
| Rebuild in rounds | O(n) | Passes; copies the string each round | |
| Two pointers, one pass | O(n) | Best; each digit written once |
n = how many digits are counted.
Edge cases to test
- n of 1, 2 or 3. The seed already covers them: the answer is 1 in all three cases.
- Overshoot. With n = 8 the last group writes a ninth digit; it must not be counted.
- Largest n. n = 100,000 is still one quick pass.
Common mistakes
- Starting the reader at index 1 instead of 2, which reads the seed's own groups again.
- Counting the 1s of the whole built string instead of the first n digits.
- Choosing the next digit from s[i] instead of flipping the last digit written.
How to talk through it
- 1Clarify. Is the string fixed (always starting with 1)? Do we count only the first n digits?
- 2Explain the self-reference. Write out 1 22 11 2 1 and its group sizes so the rule is clear.
- 3Name the two pointers. One reads a group size, the end of the string writes the group; the writer stays ahead.
- 4Code it. Seed 1, 2, 2, start the reader at index 2, flip the digit for each new group.
- 5Test out loud. Run n = 1, n = 7 and n = 8 for the overshoot.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?