TikTok Coding Interview / OA: Score of Parentheses

14 Views
No Comments

Given a balanced parentheses string s, return the score of the string.

The score of a balanced parentheses string is based on the following rules:

  • () 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

Example 4:

Input: s = "(()(()))"
Output: 6

This problem asks you to compute the score of a balanced parentheses string using three simple rules: "()" scores 1, concatenation adds scores, and wrapping a balanced string in parentheses doubles its score. A typical solution uses a stack or a running-count approach to track nesting and accumulate the contribution of each primitive "()" pair. The key is to distinguish between adjacent groups and nested groups while scanning the string.

END
 0