Editor

Longest Balanced Bracket Run

#387 · Dynamic programming · Advanced · 140 XP · about 25 min

A string of round brackets is balanced when every opening bracket is closed later by its own closing bracket, like "(())()". Given a string s made only of ( and ) that may not be balanced, write longest_balanced(s) that returns the length of its longest balanced substring (a run of consecutive characters). Return 0 if there is none.

Examples

longest_balanced("(()")        # returns 2
longest_balanced(")(()())((")  # returns 6
longest_balanced("())(())")    # returns 4
longest_balanced("))((")       # returns 0

In the second example the run "(()())" in the middle is balanced.

Constraints

  • 0 <= len(s) <= 100000
  • s holds only the characters ( and ).

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.