Ctrl K

Brackets in Two Colors

Medium
You are given a balanced bracket string brackets made of ( and ). Its depth is the largest number of pairs nested inside one another: ()() has depth 1, (()(())) has depth 3, and the empty string has depth 0. Each pair of brackets must be put into one of two groups, 0 or 1 (both brackets of a pair go to the same group). The brackets of each group, read in their original order, form a balanced string too. The goal is to make the larger of the two groups' depths as small as possible. There are usually several such splits, so one specific split is required: top-level pairs (not nested in any other pair) go to group 0, and every pair sitting directly inside another pair goes to the group opposite to that outer pair's group. This split is always optimal. Return a list of length len(brackets) whose i-th element is the group of the bracket brackets[i].
Example 1
brackets="((()))" → [0, 1, 0, 0, 1, 0]

The outer pair goes to group 0, the middle one to 1, the inner one back to 0. Group 0 is (()) with depth 2, group 1 is () with depth 1. Keeping everything in one group would give depth 3.

Example 2
brackets="()(())" → [0, 0, 0, 1, 1, 0]

Both top-level pairs go to group 0, the pair nested in the second one goes to group 1. Both groups have depth 1.

Example 3
brackets="()" → [0, 0]
Constraints
  • 1 ≤ len(brackets) ≤ 10⁴
  • brackets is a balanced string of ( and )
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTidy a Folder Route MediumFour-Operation Calculator MediumEvery Letter Once MediumChecking a Tree Record With Hash Marks MediumLongest Path to a File Medium
loading Python…
Input
brackets="((()))"
Expected
[0, 1, 0, 0, 1, 0]

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