Title: #481 - Magical String - LeetCode JavaScript Solutions
Open Graph Title: #481 - Magical String - LeetCode JavaScript Solutions
X Title: #481 - Magical String - LeetCode JavaScript Solutions
Description: A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concaten...
Open Graph Description: A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concaten...
X Description: A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concaten...
Keywords:
Opengraph URL: https://leetcodejavascript.com/solutions/magical-string
Domain: leetcodejavascript.com
{"@context":"https://schema.org","@type":"Code","url":"https://leetcodejavascript.com/solutions/magical-string","name":"#481 - Magical String - LeetCode JavaScript Solutions","description":"A magical string s consists of only '1' and '2' and obeys the following rules: The string s is magical because concaten...","programmingLanguage":"JavaScript","codeRepository":"https://github.com/JoshCrozier/leetcode-javascript","codeSampleType":"JavaScript","text":"/**\n * @param {number} n\n * @return {number}\n */\nvar magicalString = function(n) {\n if (n <= 0) return 0;\n if (n <= 3) return 1;\n\n const stack = [1, 2, 2];\n let result = 1;\n\n for (let i = 2, num = 1; stack.length < n; i++) {\n for (let j = 0; j < stack[i]; j++) {\n stack.push(num);\n if (num === 1 && stack.length <= n) {\n result++;\n }\n }\n num = num === 1 ? 2 : 1;\n }\n\n return result;\n};","keywords":"LeetCode 481, #481 - Magical String, Medium, JavaScript solution","learningResourceType":"Code","isAccessibleForFree":true,"educationalLevel":"intermediate","interactivityType":"mixed"}
| author | LeetCodeJavascript.com |
| og:type | article |
| og:image | https://leetcodejavascript.com/og-image.jpg |
| og:site_name | LeetCode JavaScript Solutions |
| twitter:card | summary_large_image |
| twitter:url | https://leetcodejavascript.com/solutions/magical-string |
| twitter:image | https://leetcodejavascript.com/og-image.jpg |
| twitter:creator | @joshcrozier |
| theme-color | #1f2937 |
Links:
| LeetCodeJavascript.com | https://leetcodejavascript.com/ |
| Star on GitHub | https://github.com/JoshCrozier/leetcode-javascript |
| Back to all solutions | https://leetcodejavascript.com |
| View on LeetCode | https://leetcode.com/problems/magical-string/ |
| View on GitHub | https://github.com/JoshCrozier/leetcode-javascript/blob/master/solutions/0481-magical-string.js |
| String | https://leetcodejavascript.com/tags/string |
| Two Pointers | https://leetcodejavascript.com/tags/two-pointers |
| Josh Crozier | https://joshcrozier.com |
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow