-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0481-magical-string.js
More file actions
39 lines (33 loc) · 869 Bytes
/
0481-magical-string.js
File metadata and controls
39 lines (33 loc) · 869 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Magical String
* Time Complexity: O(n)
* Space Complexity: O(n)
*/
var magicalString = function (n) {
if (n === 0) {
return 0;
}
if (n <= 3) {
return 1;
}
const generatedSequence = [1, 2, 2];
let onesCount = 1;
let readPointer = 2;
let digitToCreate = 1;
while (generatedSequence.length < n) {
let repeatCount = generatedSequence[readPointer];
let currentAppendCount = 0;
while (currentAppendCount < repeatCount) {
if (generatedSequence.length < n) {
generatedSequence.push(digitToCreate);
if (digitToCreate === 1) {
onesCount++;
}
}
currentAppendCount++;
}
readPointer++;
digitToCreate = (digitToCreate === 1) ? 2 : 1;
}
return onesCount;
};