Magical String - Problem

A magical string s consists of only '1' and '2' and obeys the following rule:

The string s is magical because concatenating the sequence of lengths of its consecutive groups of identical characters generates the string itself.

For example, the first few elements of the magical string are s = "1221121221221121122……"

If we group the consecutive 1's and 2's in s, it will be:

"1 22 11 2 1 22 1 22 11 2 11 22 ......"

Counting the occurrences of 1's or 2's in each group yields the sequence:

"1 2 2 1 1 2 1 2 2 1 2 2 ......"

You can see that concatenating the occurrence sequence gives us s itself.

Given an integer n, return the number of 1's in the first n characters in the magical string s.

Input & Output

Example 1 — Basic Case
$ Input: n = 6
Output: 3
💡 Note: Magical string: "122112" → Groups: "1 22 11 2" → First 6 chars have three 1's at positions 0, 3, 4
Example 2 — Small Input
$ Input: n = 1
Output: 1
💡 Note: First character of magical string is '1', so count is 1
Example 3 — Longer Sequence
$ Input: n = 10
Output: 5
💡 Note: Magical string: "1221121221" → Contains 5 ones at positions 0, 3, 4, 7, 8

Constraints

  • 1 ≤ n ≤ 105

Visualization

Tap to expand
Magical String: Self-Describing GenerationInput: n = 6Magical String:122112Group Lengths:1221Groups:1×12×21×2String describes its own group structure!Count of 1s in first 6 chars: 3
Understanding the Visualization
1
Input
Given n = 6, need count of 1s in first 6 characters
2
Self-Generation
String describes its own group lengths: 1,2,2,1,1,2...
3
Count Result
First 6 chars '122112' contain 3 ones
Key Takeaway
🎯 Key Insight: The magical string is self-describing - it contains the lengths of its own consecutive character groups
Asked in
Google 15 Facebook 8
12.5K Views
Medium Frequency
~15 min Avg. Time
324 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen