Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Score of Parentheses

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "856" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given a balanced parentheses string s, return the score of the string. The score of a balanced parentheses string is based on the following rule: "()" has score 1. AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. Example 1: Input: s = "()" Output: 1 Example 2: Input: s = "(())" Output: 2 Example 3: Input: s = "()()" Output: 2 Constraints: 2 <= s.length <= 50 s consists of only '(' and ')'. s is a balanced parentheses string.

Explanation

Here's an efficient solution to calculate the score of a balanced parentheses string, along with explanations and code:

  • Stack-based Approach: Use a stack to keep track of the current score and nesting depth. When encountering an opening parenthesis '(', push the current score onto the stack and reset the current score to 0. When encountering a closing parenthesis ')', pop the previous score from the stack and update the current score based on the rule 2 * current_score (if current_score > 0) or 1 otherwise. Add the updated score to the previous score.

  • Iterative Calculation: The string is parsed char by char to facilitate the stack based approach.

  • Leverage balanced nature: The fact that the parenthesis are balanced is key to avoid edge cases and simplify the calculations.

  • Runtime and Space Complexity:

    • Runtime Complexity: O(n), where n is the length of the input string.
    • Space Complexity: O(n), due to the stack. However, in the worst case (e.g., "((((()))))"), the stack's size is proportional to the nesting depth, which is bounded by the length of the string.

Code

    def scoreOfParentheses(s: str) -> int:
    """
    Calculates the score of a balanced parentheses string.

    Args:
        s: The balanced parentheses string.

    Returns:
        The score of the string.
    """

    stack = [0]  # Initialize stack with 0 (base score)
    for char in s:
        if char == '(':
            stack.append(0)  # Push current score onto stack, reset to 0
        else:  # char == ')'
            top = stack.pop()
            stack[-1] += max(2 * top, 1)  # Update previous score

    return stack[0]

More from this blog

C

Chatmagic blog

2894 posts