Score of Parentheses

MediumStackstack

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a non-empty balanced parentheses string s (only ( and )). Its score is defined recursively: - "()" scores 1. - A concatenation AB of two balanced strings scores score(A) + score(B). - A wrapped string (A) scores 2 * score(A). Return the score of s. Aim for O(n) time; O(1) extra space is possible.

Examples

Input: s = "(()(()))"
Output: 6
Inside the outer pair, "()" scores 1 and "(())" scores 2, so the contents score 3 and the outer pair doubles it to 6.
Input: s = "()()"
Output: 2
Two side-by-side "()" pairs add: 1 + 1.
Input: s = "((()))"
Output: 4
Each wrapping pair doubles: 1, then 2, then 4.

Constraints

  • 2 <= s.length <= 50
  • `s` consists only of `(` and `)`.
  • `s` is a balanced parentheses string.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More stack problems