Problem
A magical string s
consists of only '1'
and '2'
and obeys the following rules:
- The string s is magical because concatenating the number of contiguous occurrences of characters
'1'
and'2'
generates the strings
itself.
The first few elements of s
is 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 ......"
and the occurrences of 1
’s or 2
’s in each group are "1 2 2 1 1 2 1 2 2 1 2 2 ......"
. You can see that the occurrence sequence is s
itself.
Given an integer n
, return the number of 1
’s in the first n
number in the magical string s
.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Iteration
To solve the problem of counting the number of ‘1’s in the first n
elements of the magical string s
, we need to generate the magical string up to the required length and count the ‘1’s.
The magical string s
starts with “122”. We will:
- Generate the magical string iteratively using the rules described.
- Use a pointer to control where to read the number of occurrences (from 1, 2 sequence).
- Append the generated characters based on the number of occurrences specified by the pointer.
- Count the number of ‘1’s in the first
n
characters of the string.
Here are the steps in details:
- Initialize the magical string with “122”.
- Use a pointer to iterate over the sequence and determine how many of each character (‘1’ or ‘2’) to add next.
- Alternate between adding ‘1’s and ‘2’s.
- Count the ‘1’s in the first
n
characters once the string reaches or exceeds lengthn
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. We generate and check each character up to the required lengthn
. - 🧺 Space complexity:
O(n)
,due to the storage of the generated magical string.