← Infosys bank

Infosys · Question 48 · Stacks

Score of Parentheses

StacksC++code⏱ O(n)💾 O(n)
Service-based

Problem

Compute score of parentheses using rules: () = 1, AB = A+B, (A) = 2×A.

Approach

Use a stack to accumulate scores. On '(' push 0, on ')' pop and compute.

Time O(n)Space O(n)

How it works

  1. 1'(' opens a fresh frame.
  2. 2')' closes it into max(2v, 1) added upward.

Sample input / output

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

Constraints

Balanced parentheses; 2 <= length <= 50.

Solution — read it, then walk it

Time O(n)Space O(n)Loops 1Branches 1Returns 2source · C++
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTinclude <iostream>include <string>include <stack>include <algorithm>using namespace stdDEFINEscoreOfParentheses(stringS)stack<int> stst.push(0)for (char c : S)if (c == '(')st.push(0)} elseRETURN st.top()DEFINE main()cout <<scoreOfParentheses("(()(()))")<< endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/17

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits