Ctrl K

A Balanced Route Through the Grid

Hard
You are given an m × n grid grid where every cell holds a bracket, ( or ). A route starts at the top-left cell, ends at the bottom-right cell and moves either right or down at every step. Writing down the brackets of its cells in order gives a string. A bracket string is *balanced* if every opening bracket can be paired with a closing bracket after it so that the pairs do not cross: (())() is balanced, while )( and (() are not. Return True if some route produces a balanced string, and False otherwise.
Example 1
grid=[['(', '(', ')'], [')', '(', ')']] → True

Going right, right, down collects (()), a balanced string.

Example 2
grid=[['(', '(', ')'], ['(', ')', '(']] → False

Every route ends on a cell with (, and a balanced string cannot end with an opening bracket.

Example 3
grid=[['(', ')', '('], [')', '(', ')'], ['(', ')', ')'], [')', '(', ')']] → True
Constraints
  • 1 ≤ m, n ≤ 100
  • All rows have the same length
  • Every cell is ( or )
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Solid Panel Block HardCrossing the Cave HardLongest Uphill Walk HardWeeks of Rest by Flight HardBerry Field Round Trip Hard
loading Python…
Input
grid=[['(', '(', ')'], [')', '(', ')']]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 42 tests on the server, hidden ones included.