A magical string s
is a string only consisting of ‘1’ and ‘2’ and obeys the following rules:
s
is unfolded as follows: s = “1221121221221121122……”Given an integer n
, return the number of ‘1’s in the first n
number in the magical string.
Example:
Input: n = 6
Output: 3
Explanation: The first 6 elements of magical string s are "122112" and it contains three 1's, so return 3.
Constraints:
n
characters if n
is greater than the length of the string described in the examples?
s
defined in the unfolded manner continues indefinitely as per the folding rules.s = "122"
.s
.n
characters.public class Solution {
public int magicalString(int n) {
if (n <= 0) return 0;
if (n <= 3) return 1; // Base case, since "122" contains one '1' in the first 3 chars.
StringBuilder s = new StringBuilder("122");
int count = 1; // Initially, we have one '1'.
int head = 2, tail = 3; // head for reading, tail for adding new values.
while (s.length() < n) {
int numToAdd = s.charAt(tail - 1) - '0'; // Determine the number to add based on last character in `s`
int times = s.charAt(head++) - '0'; // Determine how many times to add it.
for (int i = 0; i < times; i++) {
s.append(numToAdd);
if (numToAdd == 1 && s.length() <= n) {
count++;
}
}
tail++;
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.magicalString(6)); // Output: 3
}
}
n
characters:
O(n)
for the above approach since every new section is computed and appended directly proportional to n
values.Therefore, the overall time complexity for this solution is approximately O(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?