Ctrl K

A Sequence That Describes Itself

Medium
Consider the infinite sequence of digits 1 and 2 that begins like this: 1 2 2 1 1 2 1 2 2 1 2 2 1 1 2 1 1 2 2 … Split it into runs of equal adjacent digits: 1 | 22 | 11 | 2 | 1 | 22 | 1 | 22 | 11 | …. Writing down the run lengths in order gives 1 2 2 1 1 2 1 2 2 …, which is the sequence itself. The runs alternate between ones and twos. The opening 1 2 2 together with this rule determines the whole sequence. Given length, count the ones among the first length digits of the sequence.
Example 1
length=9 → 4

The first 9 symbols are 122112122, which contain four ones.

Example 2
length=3 → 1

The sequence starts with 122, so there is a single one.

Example 3
length=20 → 10
Constraints
  • 1 ≤ length ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Mirror Fragment MediumWords in Reverse Order MediumExactly One Edit Apart MediumWhich Release Is Newer MediumReverse the Word Order in Place Medium
loading Python…
Input
length=9
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 44 tests on the server, hidden ones included.