MediumNo. 0856

Score of Parentheses — LeetCode 856 Python Solution

Pattern
Stack
Topics
Stack, String
Reading time
2 min

The problem

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.

Example

Input
s = "()"
Output
1

Python solution

PythonSolution
class Solution:
    def scoreOfParentheses(self, s: str) -> int:
        ans = d = 0
        for i, c in enumerate(s):
            if c == '(':
                d += 1
            else:
                d -= 1
                if s[i - 1] == '(':
                    ans += 1 << d
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 856. Score of Parentheses is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0020Valid ParenthesesEasy
0071Simplify PathMedium
0224Basic CalculatorHard
0227Basic Calculator IIMedium
0331Verify Preorder Serialization of a Binary TreeMedium
0385Mini ParserMedium

Frequently asked questions

How hard is LeetCode 856. Score of Parentheses?

LeetCode 856. Score of Parentheses is rated Medium on LeetCode.

What is the time complexity of LeetCode 856. Score of Parentheses?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 856. Score of Parentheses?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 856. Score of Parentheses cover?

LeetCode 856. Score of Parentheses is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.