KatInterview

481. Magical String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem defines a "magical string" s composed of only '1's and '2's. The string is self-referential: if you write down the counts of consecutive identical characters, you get the string s back. For example, s starts as "122112...". Grouping gives "1", "22", "11", "2", ... The counts of these groups are 1, 2, 2, 1, ..., which is the beginning of s itself.

Solution

Magical String in Python

class Solution:
    def magicalString(self, n: int) -> int:
        # Base cases: for n=1 ("1"), n=2 ("12"), n=3 ("122"), there's one '1'.
        if n <= 3:
            return 1

        # Initialize the string with the base prefix.
        # Python lists grow dynamically, so no need to pre-allocate size.
        s = [1, 2, 2]
        
        head = 2        # Pointer for reading counts from s.
        tail = 3        # Represents the current length of s, and the index to write at.
        num_to_write = 1 # The number to write, alternates between 1 and 2.
        ones_count = 1   # Count of '1's in the first n elements.

        # Generate the string until its length is at least n.
        while tail < n:
            # The number at s[head] determines how many times to write the current num_to_write.
            count = s[head]
            
            # Write num_to_write 'count' times.
            for _ in range(count):
                # Only operate if we are still within the first n characters.
                if tail < n:
                    if num_to_write == 1:
                        ones_count += 1
                    s.append(num_to_write)
                    tail += 1
                else:
                    # If tail reaches n, we have all the characters we need.
                    break
            
            # Flip the number to write for the next group (1 -> 2, 2 -> 1).
            num_to_write = 3 - num_to_write
            # Move the head pointer to get the next count.
            head += 1
            
        return ones_count

Magical String in Java

class Solution {
    public int magicalString(int n) {
        // Base cases: for n=1 ("1"), n=2 ("12"), n=3 ("122"), there's one '1'.
        if (n <= 3) {
            return 1;
        }

        // Use an array to store the string. Allocate n+1 to be safe, as tail can reach n.
        int[] s = new int[n + 1];
        s[0] = 1; s[1] = 2; s[2] = 2;
        
        int head = 2;       // Pointer for reading counts from s.
        int tail = 3;       // Pointer for writing new numbers to s.
        int numToWrite = 1; // The number to write, alternates between 1 and 2.
        int onesCount = 1;  // Count of '1's in the first n elements.

        // Generate the string until its length is at least n.
        while (tail < n) {
            // The number at s[head] determines how many times to write the current numToWrite.
            int count = s[head];
            
            // Write numToWrite 'count' times.
            for (int i = 0; i < count; i++) {
                // Only operate if we are still within the first n characters.
                if (tail < n) {
                    s[tail] = numToWrite;
                    if (numToWrite == 1) {
                        onesCount++;
                    }
                    tail++;
                } else {
                    // If tail reaches n, we have all the characters we need.
                    break;
                }
            }
            
            // Flip the number to write for the next group (1 -> 2, 2 -> 1).
            numToWrite = 3 - numToWrite;
            // Move the head pointer to get the next count.
            head++;
        }
        
        return onesCount;
    }
}

Magical String in C++

class Solution {
public:
    int magicalString(int n) {
        // Base cases: for n=1 ("1"), n=2 ("12"), n=3 ("122"), there's one '1'.
        if (n <= 3) {
            return 1;
        }

        // Use a vector to store the string. Allocate n+1 to be safe, as tail can reach n.
        std::vector<int> s(n + 1);
        s[0] = 1; s[1] = 2; s[2] = 2;
        
        int head = 2;       // Pointer for reading counts from s.
        int tail = 3;       // Pointer for writing new numbers to s.
        int numToWrite = 1; // The number to write, alternates between 1 and 2.
        int onesCount = 1;  // Count of '1's in the first n elements.

        // Generate the string until its length is at least n.
        while (tail < n) {
            // The number at s[head] determines how many times to write the current numToWrite.
            int count = s[head];
            
            // Write numToWrite 'count' times.
            for (int i = 0; i < count; ++i) {
                // Only operate if we are still within the first n characters.
                if (tail < n) {
                    s[tail] = numToWrite;
                    if (numToWrite == 1) {
                        onesCount++;
                    }
                    tail++;
                } else {
                    // If tail reaches n, we have all the characters we need.
                    break;
                }
            }
            
            // Flip the number to write for the next group (1 -> 2, 2 -> 1).
            numToWrite = 3 - numToWrite;
            // Move the head pointer to get the next count.
            head++;
        }
        
        return onesCount;
    }
};

Magical String in TypeScript

function magicalString(n: number): number {
    // Base cases: for n=1 ("1"), n=2 ("12"), n=3 ("122"), there's one '1'.
    if (n <= 3) {
        return 1;
    }

    // Use an array to store the string. Allocate n+1 to be safe, as tail can reach n.
    const s: number[] = new Array(n + 1);
    s[0] = 1; s[1] = 2; s[2] = 2;
    
    let head = 2;       // Pointer for reading counts from s.
    let tail = 3;       // Pointer for writing new numbers to s.
    let numToWrite = 1; // The number to write, alternates between 1 and 2.
    let onesCount = 1;  // Count of '1's in the first n elements.

    // Generate the string until its length is at least n.
    while (tail < n) {
        // The number at s[head] determines how many times to write the current numToWrite.
        const count = s[head];
        
        // Write numToWrite 'count' times.
        for (let i = 0; i < count; i++) {
            // Only operate if we are still within the first n characters.
            if (tail < n) {
                s[tail] = numToWrite;
                if (numToWrite === 1) {
                    onesCount++;
                }
                tail++;
            } else {
                // If tail reaches n, we have all the characters we need.
                break;
            }
        }
        
        // Flip the number to write for the next group (1 -> 2, 2 -> 1).
        numToWrite = 3 - numToWrite;
        // Move the head pointer to get the next count.
        head++;
    }
    
    return onesCount;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.