#856

Score of Parentheses

Medium
StringStackStackRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a stack to keep track of the scores as we parse through the string. This method is efficient and leverages the structure of the parentheses to compute scores in a single pass.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a stack to hold scores and a variable for the current score.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: For each '(', push the current score onto the stack and reset the score to 0.
  4. 4Step 4: For each ')', pop from the stack and update the score based on the popped value, doubling it if it was preceded by a '('.
solution.py10 lines
1def scoreOfParentheses(s):
2    stack = []
3    score = 0
4    for char in s:
5        if char == '(': 
6            stack.append(score)
7            score = 0
8        else:
9            score = stack.pop() + max(2 * score, 1)
10    return score

Complexity note: The time complexity is O(n) because we traverse the string once, and the space complexity is O(n) due to the stack used to store scores.

  • 1Using a stack helps manage nested structures effectively.
  • 2Understanding the scoring rules is crucial for implementing the logic correctly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.