Score a balanced string of square brackets by these rules:
[] scores 1.XY (two adjacent balanced groups) scores score(X) + score(Y).[X] (a group wrapping a balanced X) scores 2 * score(X).Return the total score. The input is always a valid balanced bracket string.
nestingScore(s)
Input format: a string of [ and ].
"[]" // → 1
"[][]" // → 2
"[[]]" // → 2
"[[][]]" // → 4
The scoring rules are recursive: a group's score depends on what's inside it, and adjacent groups add their scores. That points to tracking "the score accumulated so far at this level of nesting" separately for each level, since an inner group's score must be finalized and folded into its parent's total before the parent continues.
In [[][]], the outer bracket wraps two sibling [] groups. While inside it, you need a running total of siblings seen so far at that level (1 + 1 = 2). That total belongs to the outer level — a different accumulator from whatever would track further nesting inside one of the inner groups. Each level needs its own private running total, combined correctly when it closes.
Each stack entry is the running score for the current level:
[, push a fresh 0 for the new level.], pop the accumulator for the level that just finished. If it's 0, the group was an empty [] pair — scores 1. If non-zero, it wrapped content scoring X — scores 2 * X. Either way, add that into the new top of the stack, the parent's accumulator.The two rules — wrapping doubles, adjacency adds — are naturally recursive, and a recursive parser would work too. But the stack-of-accumulators does the same thing iteratively, in one pass, since the stack stands in for the call stack: each push is like entering a nested call for a new group, each pop-and-add-to-parent is like that call returning its result. Any recursive, nested scoring problem can often flatten into a single pass using a stack that holds pending results per nesting level.
def nesting_score(s):
stack = [0]
for ch in s:
if ch == "[":
stack.append(0)
else:
top = stack.pop()
add = 2 * top if top > 0 else 1
stack[-1] += add
return stack[0]
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.