Problem 1111

Abstract / Summary

Find the deepest level of nested pairs in two valid parentheses strings combined.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1111.py

class Solution:
    def maxDepthAfterSplit(self, seq: str) -> List[int]:
        a = b = 0
        for c in seq:
            left  = a < b    # 1 if True else 0
            right = left ^ 1 # same as 1 - left

            if c == "(":
                a +=  left
                b +=  right
                yield right
            else:
                a -=  right
                b -=  left
                yield left
15 lines | 433 bytes | submitted March 21, 2024 | GitHub   14% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (40k+ submissions).

Typical patterns to solve this problem:
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that processes a parenthesis string and produces a sequence of binary assignments indicating to which of two groups each character belongs. The algorithm walks through the input once, maintaining two counters that represent the current nesting depth of each group. By leveraging simple arithmetic and bitwise operations, the method yields the group index for every character while preserving the original nesting structure.

Key Steps

The core of the algorithm is the single pass over the input string. At the start of the method two integer variables, a and b, are initialized to zero. These variables track the depth of open parentheses assigned to group 0 (a) and group 1 (b).

a = b = 0

For each character c in the sequence, the code first determines which group currently has the smaller depth. The expression a < b evaluates to a Boolean, which is implicitly converted to 1 for True and 0 for False. This value is stored in left. The complementary value, representing the other group, is computed with an XOR against 1.

left  = a < b    # 1 if True else 0
right = left ^ 1 # opposite of left

When the character is an opening parenthesis '(', the algorithm increments the depth counter of the group indicated by left and the depth counter of the opposite group by right. The group index that receives the character is right, which is yielded to the caller.

if c == "(":
    a +=  left
    b +=  right
    yield right

When the character is a closing parenthesis ')', the depth counters are decremented in the opposite direction: the group that received the matching opening parenthesis is identified by right, and the other group by left. The group index that should receive the closing parenthesis is left, which is yielded.

else:
    a -=  right
    b -=  left
    yield left

The use of yield makes the method a generator, allowing the caller to iterate over the resulting assignment list without constructing an intermediate array.

Edge Cases Handled

The algorithm correctly processes strings that consist entirely of opening parentheses, entirely of closing parentheses, or any mixture thereof, because the depth counters are updated symmetrically for both groups. When the input string is empty, the loop body is never executed and the generator produces no output, which aligns with the expectation of an empty assignment list. The comparison a < b ensures that when both groups have equal depth, the opening parenthesis is assigned to group 0 (left becomes 0, right becomes 1). This deterministic tie-breaking guarantees a consistent split even for perfectly balanced strings. The decrement logic mirrors the increment logic, so each closing parenthesis is matched with the correct group regardless of nesting depth, preventing mismatches in depth tracking.

Performance Optimizations

The implementation achieves high efficiency by avoiding auxiliary data structures such as stacks or explicit depth arrays. Maintaining only two integer counters reduces memory overhead to a constant amount. The decision of which group to assign a parenthesis is performed with a single comparison and a bitwise XOR, both of which are inexpensive operations. By using a generator (yield) rather than building a list, the method emits results on demand, which can be advantageous when the caller consumes the output incrementally or when the result is large. The tight loop body consists of a few arithmetic updates and a conditional branch, enabling the interpreter to execute the algorithm with minimal overhead per character.

written by openai gpt

ELI5 - Simplified Explanation

Think of a bag full of open and closed parentheses. The code acts like a little helper that decides which bucket each one belongs to, either bucket zero or bucket one. It keeps track of how many open brackets are already in each bucket by using two counters.

When a new open parenthesis arrives, the code checks which bucket currently has fewer items. It puts the new parenthesis into the emptier bucket to keep things balanced. If a closed parenthesis appears, it removes the matching one from the bucket that was holding it.

By switching between these two buckets, the code splits the long string of parentheses into two shorter groups. This makes sure that no matter how deep the nests of parentheses get, neither bucket ever has too many layers stacked inside. Each bracket gets a label of zero or one to show which team it is on.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.27 | σ = 1.85

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lzl124631x C++
suxrobGM C#
varunu28 Java
27 links | 16 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   March 21, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality