Magicsheet logo

Maximum Nesting Depth of Two Valid Parentheses Strings

Medium
12.5%
Updated 8/1/2025

Asked by 3 Companies

Maximum Nesting Depth of Two Valid Parentheses Strings

What is this problem about?

The Maximum Nesting Depth of Two Valid Parentheses Strings coding problem gives you a valid parentheses string (VPS) and asks you to split it into two VPS strings A and B such that the maximum nesting depth among the two is minimized. You assign each parenthesis in the original string to either A or B (preserving order) and want to balance the depths.

Why is this asked in interviews?

Bloomreach, Amazon, and Google use this problem to evaluate greedy reasoning about balanced load distribution. The optimal strategy — assign alternating parentheses to A and B at the same depth — is elegant and provably optimal. Candidates who derive this greedy insight demonstrate the ability to think about distribution problems structurally rather than through exhaustive search.

Algorithmic pattern used

Greedy with depth tracking: Scan the string while maintaining a running depth. When you see (, increment depth. When you see ), decrement depth. Assign each ( and its matching ) to A if they are at an odd depth level, or B if at an even depth level (or vice versa). This alternating assignment ensures neither A nor B ever has a nesting depth greater than ceil(max_depth / 2). Use a bit mask to decide assignment: (depth - 1) % 2 for ( and depth % 2 for ).

Example explanation

String: "(()())"

  • ( at depth 1: assign to A (odd).
  • ( at depth 2: assign to B (even).
  • ) at depth 2: assign to B.
  • ( at depth 2: assign to B.
  • ) at depth 2: assign to B.
  • ) at depth 1: assign to A.
  • A = "()" (the outer shell), B = "(())" (inner).

Wait — B = "()()" actually since the two inner pairs go to B. Max depth of A = 1, max depth of B = 1. Original max depth = 2. We halved it. Output: seq[0]=0,seq[1]=1,seq[2]=1,seq[3]=1,seq[4]=1,seq[5]=0.

Common mistakes candidates make

  • Assigning based on position, not depth: The assignment must be based on the current depth level, not just the index, to guarantee balanced split.
  • Not handling the ) symmetrically: The matching ) must be assigned to the same partition as its ( to maintain validity of each partition.
  • Returning wrong format: The problem may ask for a binary array (0 or 1 per character). Ensure the output format matches exactly.

Interview preparation tip

For the String Stack interview pattern, depth-based partitioning problems often have elegant greedy solutions based on alternating levels. When asked to split a structure into two parts to minimize the maximum of some metric, think about "round-robin" or "alternating" assignment by rank or level. This reduces max depth to roughly half in one pass.

Similar Questions