A popular coding interview problem, Score of Parentheses, demystified through step-by-step intuition and two efficient solutions in Java, Python, and C++.
The problem asks to compute the score of a balanced parentheses string based on three rules:
"()"has score 1.- Concatenation of parentheses adds their scores (e.g.,
"()()"= 2). - Nesting multiplies the score (e.g.,
"(())"= 2).
Stack-Based Approach
The stack approach simulates the scoring by pushing a placeholder for each '(' and updating scores on encountering ')'. When a ')' is found:
- If the top of stack is
'(', pop it and push1. - Else, pop all numbers until
'(', sum them, double the sum, pop'(', and push the doubled result. At the end, sum all numbers in the stack.
Space-Optimized Approach
By tracking the current nesting depth, we can compute the score without extra space. Whenever we see "()" at depth d, we add 2^d to the total. This works because each nested "()" contributes 2^{depth-1}.
Algorithm:
- Initialize
result = 0,depth = 0. - Iterate over each character in the string.
- If
char == '(', incrementdepth. - Else, decrement
depthand if the previous character was'(', add(1 << depth)(i.e.,2^{depth}) to result.
This approach runs in O(n) time and O(1) space, making it ideal for interviews.
Why it matters: The problem teaches pattern recognition for stack usage and the power of mathematical optimization, common in technical interviews for companies like Google, Amazon, and Microsoft.