Advertisement

Score of Parentheses - LeetCode 856 Solution

Score of Parentheses - Complete Solution Guide

Score of Parentheses is LeetCode problem 856, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

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 par

Detailed Explanation

The problem asks us to calculate the score of a balanced parentheses string based on the given rules: '()' has a score of 1, 'AB' has a score of A + B, and '(A)' has a score of 2 * A. The input is guaranteed to be a balanced parentheses string containing only '(' and ')', and the length of the string is between 2 and 50. We need to return the integer score of the input string.

Solution Approach

The solution maintains a 'depth' variable to track the current nesting level. When an opening parenthesis '(' is encountered, the depth is incremented. When a closing parenthesis ')' is encountered, the depth is decremented. If the previous character was an opening parenthesis, it indicates that a '()' sub-string has been found at the current depth. The score is then increased by 2 to the power of the current depth (which is equivalent to 1 << depth). This directly computes the score according to the problem's recursive rules without explicitly using recursion or stack.

Step-by-Step Algorithm

  1. Step 1: Initialize `score` and `depth` to 0.
  2. Step 2: Iterate through the input string `s`.
  3. Step 3: If the current character `s[i]` is '(', increment `depth`.
  4. Step 4: If the current character `s[i]` is ')', decrement `depth`.
  5. Step 5: If the previous character `s[i-1]` was '(', add `1 << depth` to `score`. This is equivalent to 2 raised to the power of `depth`.
  6. Step 6: After iterating through the entire string, return the final `score`.

Key Insights

  • Insight 1: The depth of parentheses nesting determines the multiplier. Each '(' increases depth, and each ')' decreases it.
  • Insight 2: Whenever we encounter a ')' immediately after a '(', it represents a '()' sub-string, and its value depends on the current depth.
  • Insight 3: Instead of using recursion or stack to simulate the process described in the problem statement, we can utilize the depth to directly compute the score.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: String, Stack.

Companies

Asked at: Mountblue, Snap.