856. Score of Parentheses LeetCode Solution

In this guide, you will get 856. Score of Parentheses LeetCode Solution with the best time and space complexity. The solution to Score of Parentheses problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Score of Parentheses solution in C++
  4. Score of Parentheses solution in Java
  5. Score of Parentheses solution in Python
  6. Additional Resources
856. Score of Parentheses LeetCode Solution image

Problem Statement of Score of Parentheses

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.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

856. Score of Parentheses LeetCode Solution in C++

class Solution {
 public:
  int scoreOfParentheses(string s) {
    int ans = 0;
    int layer = 0;

    for (int i = 0; i + 1 < s.length(); ++i) {
      const char a = s[i];
      const char b = s[i + 1];
      if (a == '(' && b == ')')
        ans += 1 << layer;
      layer += a == '(' ? 1 : -1;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

856. Score of Parentheses LeetCode Solution in Java

class Solution {
  public int scoreOfParentheses(String s) {
    int ans = 0;
    int layer = 0;

    for (int i = 0; i + 1 < s.length(); ++i) {
      final char a = s.charAt(i);
      final char b = s.charAt(i + 1);
      if (a == '(' && b == ')')
        ans += 1 << layer;
      layer += a == '(' ? 1 : -1;
    }

    return ans;
  }
}
// code provided by PROGIEZ

856. Score of Parentheses LeetCode Solution in Python

class Solution:
  def scoreOfParentheses(self, s: str) -> int:
    ans = 0
    layer = 0

    for a, b in itertools.pairwise(s):
      if a + b == '()':
        ans += 1 << layer
      layer += 1 if a == '(' else -1

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.