BackmediumStackPaytmPayPal

Bounded Range Segment Calculator 5 Solution

Problem Statement

You are provided with a string s consisting of nested parentheses. The score of a valid parentheses string is defined recursively: an empty string has a score of 0; a string formed by concatenating two valid strings A and B has a score of score(A) + score(B); and a string formed by enclosing a valid string A in parentheses, i.e., "(A)", has a score of 2 * score(A). Your task is to compute the total score of the given string. The input is guaranteed to be a valid parentheses string, meaning every opening parenthesis has a corresponding closing parenthesis in the correct order.

Example 1
Input
s = "()"
Output
2

Explanation: The string is a single pair of parentheses enclosing an empty string. The score of the empty string is 0. Therefore, the score is 2 * 0 = 2.

Example 2
Input
s = "(())"
Output
4

Explanation: The outer parentheses enclose the string "()". The inner string "()" has a score of 2. Therefore, the total score is 2 * 2 = 4.

Example 3
Input
s = "()()"
Output
4

Explanation: The string is a concatenation of two valid strings: "()" and "()". The score of the first part is 2, and the score of the second part is 2. The total score is 2 + 2 = 4.

Example 4
Input
s = "(()(()))"
Output
6

Explanation: The outer parentheses enclose "()(())". The inner string is a concatenation of "()" (score 2) and "(())" (score 4). The sum of the inner scores is 2 + 4 = 6. The total score is 2 * 6 = 12? Wait, let's re-evaluate. Actually, let's trace: "(()(()))" Outer: ( A ) where A = "()(())". Score(A) = Score("()") + Score("(())") = 2 + 4 = 6. Total Score = 2 * 6 = 12. Let's pick a simpler one to avoid confusion in the example text. New Example 4: s = "(()())". Outer: ( A ) where A = "()()". Score(A) = 2 + 2 = 4. Total Score = 2 * 4 = 8.

Constraints

  • 1 <= s.length <= 3 * 10^4
  • s[i] is either '(' or ')'
  • s is a valid parentheses string
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Bounded Range Segment Calculator 5 — Problem Statement & Solution Guide

StackMediumParenthesis Score Calculator
TimeO(N)
|
SpaceO(N)

Problem Description

You are provided with a string s consisting of nested parentheses. The score of a valid parentheses string is defined recursively: an empty string has a score of 0; a string formed by concatenating two valid strings A and B has a score of score(A) + score(B); and a string formed by enclosing a valid string A in parentheses, i.e., "(A)", has a score of 2 * score(A). Your task is to compute the total score of the given string. The input is guaranteed to be a valid parentheses string, meaning every opening parenthesis has a corresponding closing parenthesis in the correct order.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Bounded Range Segment Calculator 5"

medium

WHY DOES IT MATTER?

This pattern is essential for parsing hierarchical data, such as XML, JSON, or expression trees, where the structure is defined by matching delimiters. It teaches the fundamental concept of using a stack to manage state in a linear pass, which is a cornerstone of compiler design and data processing.

OPTIMIZATION CHALLENGE

The key insight is to avoid storing the entire substring for each scope. Instead, by using a stack of integers (scores), you can compute the score incrementally. When you close a scope, you only need the score of the innermost scope, which is already computed and stored on the stack. This reduces space complexity from O(N^2) in a naive recursive approach to O(N).

REAL-WORLD CONNECTION

This is analogous to how a web browser manages the call stack for JavaScript execution or how a database engine handles nested transactions. Each opening parenthesis is like starting a new transaction or function call, and the closing parenthesis commits or returns the result, with the score representing the accumulated state or return value.

In an interview, emphasize that you are using the stack to 'remember' the context of each nesting level. Highlight that the score of a scope is determined by its contents, and the stack allows you to isolate and compute these contents independently before combining them.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The problem of calculating the score of nested parentheses is a classic application of stack-based parsing, specifically leveraging the Last-In-First-Out (LIFO) property to manage hierarchical structures. The recursive definition of the score—where concatenation implies addition and nesting implies multiplication by 2—maps directly to the structure of a stack. When we encounter an opening parenthesis '(', we push a marker onto the stack to denote the start of a new scope. When we encounter a closing parenthesis ')', we pop the corresponding opening marker and calculate the score for that specific scope. This approach effectively flattens the recursive tree structure into a linear pass, avoiding the overhead of explicit recursion or complex tree construction.

Interview Questions on This Problem

Q1How would you modify this algorithm to handle a string where the score of a nested pair is defined as the sum of the scores of its immediate children plus 1, rather than 2 * score(A)?

You would maintain a stack of scores rather than just markers. When you see '(', push 0. When you see ')', pop the top score, add 1 to it, and add the result to the new top of the stack. This transforms the multiplicative nesting into an additive accumulation, requiring careful handling of the base case for empty strings.

Q2In a distributed system, how would you parallelize the calculation of scores for a massive parentheses string of length 10^9?

You can use a divide-and-conquer approach by finding the top-level balanced segments. Each top-level segment can be processed independently in parallel. Within each segment, you can further split at the deepest nesting levels where the sub-problems are independent. The final score is the sum of the scores of all top-level segments, allowing for horizontal scaling across multiple workers.

Q3What is the time complexity of this solution, and can it be improved below O(N)?

The time complexity is O(N) because each character is processed exactly once, and each stack operation (push/pop) is O(1). It cannot be improved below O(N) because you must inspect every character to determine the structure of the string. Any algorithm that skips characters would risk missing nested structures that affect the score.

Examples

Example 1

Input

s = "()"

Output

2

Explanation: The string is a single pair of parentheses enclosing an empty string. The score of the empty string is 0. Therefore, the score is 2 * 0 = 2.

Example 2

Input

s = "(())"

Output

4

Explanation: The outer parentheses enclose the string "()". The inner string "()" has a score of 2. Therefore, the total score is 2 * 2 = 4.

Example 3

Input

s = "()()"

Output

4

Explanation: The string is a concatenation of two valid strings: "()" and "()". The score of the first part is 2, and the score of the second part is 2. The total score is 2 + 2 = 4.

Example 4

Input

s = "(()(()))"

Output

6

Explanation: The outer parentheses enclose "()(())". The inner string is a concatenation of "()" (score 2) and "(())" (score 4). The sum of the inner scores is 2 + 4 = 6. The total score is 2 * 6 = 12? Wait, let's re-evaluate. Actually, let's trace: "(()(()))" Outer: ( A ) where A = "()(())". Score(A) = Score("()") + Score("(())") = 2 + 4 = 6. Total Score = 2 * 6 = 12. Let's pick a simpler one to avoid confusion in the example text. New Example 4: s = "(()())". Outer: ( A ) where A = "()()". Score(A) = 2 + 2 = 4. Total Score = 2 * 4 = 8.

Constraints

  • 1 <= s.length <= 3 * 10^4
  • s[i] is either '(' or ')'
  • s is a valid parentheses string

Optimal Approach & Strategy

The optimized approach uses a stack to keep track of the scores of the current nesting levels. When an opening parenthesis is encountered, a new score accumulator is pushed onto the stack. When a closing parenthesis is encountered, the top score is popped, doubled (or processed according to the scoring rule), and added to the new top of the stack. This avoids substring creation and processes the string in a single pass.

Brute Force Approach

A brute force approach would involve recursively parsing the string, finding the matching closing parenthesis for each opening parenthesis, and calculating the score of the substring inside. This would involve creating new substrings for each recursive call, leading to O(N^2) time complexity due to string copying and O(N) space complexity for the recursion stack.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

PaytmPayPal

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.