4 September 2026 · Advanced track
Balance the Log
Work out the fewest opening and closing brackets needed to make a log of bracket actions fully balanced.
Every time a player opens or closes a challenge bracket, it's logged as a single character: `{` for opening one, `}` for closing one, in the order the actions happened. A perfectly balanced log opens exactly as many brackets as it closes, and never has a `}` that closes something that isn't currently open. Work through the log in order and figure out the fewest extra characters of each kind that would need to be inserted, at the best possible points, to make the whole log balanced. Return your answer as a tuple `(opens_needed, closes_needed)`. If the log is already balanced, return `(0, 0)`.
Constraints
log is a string made up only of the characters { and }log may be empty, which is already balancedA } that appears before its matching { counts as needing one extra { inserted before itAny { left unclosed at the end counts as needing one extra } inserted after it
Function signature
def brackets_to_close(log):