Leetcode 481: Magical String

grid47
grid47
Exploring patterns and algorithms
Sep 19, 2024 4 min read

A sequence where the magical string gradually forms, with each step softly glowing as the pattern emerges.
Solution to LeetCode 481: Magical String Problem

A magical string consists of only ‘1’ and ‘2’ and follows a special rule: the number of consecutive occurrences of characters ‘1’ and ‘2’ generates the string itself. Given an integer n, return the number of ‘1’s in the first n characters of the magical string.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n`, the length of the desired substring of the magical string.
Example: n = 7
Constraints:
• 1 <= n <= 10^5
Output: Return the number of '1's in the first `n` characters of the magical string.
Example: Output: 4
Constraints:
• The result will be a non-negative integer.
Goal: Generate the magical string up to `n` characters and count the number of '1's.
Steps:
• 1. Start with the base string '122'.
• 2. Generate the magical string by adding segments based on the number of previous occurrences.
• 3. For each segment, append the opposite digit (either '1' or '2') based on the previous occurrence.
• 4. Once the string is generated up to `n` characters, count the number of '1's in the substring.
Goal: The constraints on the input are as follows.
Steps:
• 1 <= n <= 10^5
Assumptions:
• The value of `n` will always be within the given range.
Input: n = 7
Explanation: The first 7 characters of the magical string are '1221121'. This string has four '1's, so the output is 4.

Input: n = 3
Explanation: The first 3 characters of the magical string are '122'. This string has two '1's, so the output is 2.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus