Leetcode 1111: Maximum Nesting Depth of Two Valid Parentheses Strings

grid47
grid47
Exploring patterns and algorithms
Jul 18, 2024 5 min read

A string consisting of only ‘(’ and ‘)’ characters is considered a valid parentheses string (VPS) if it satisfies the following conditions: it is empty, can be split into two valid VPS’s, or can be written in the form of ‘(A)’ where A is a VPS. You are given a VPS string seq. The task is to split it into two subsequences, A and B, such that both A and B are valid parentheses strings. The goal is to minimize the maximum nesting depth between A and B, and you need to return an array where each element is 0 if the character is part of A, and 1 if it’s part of B.
Problem
Approach
Steps
Complexity
Input: The input is a string `seq` consisting only of '(' and ')' characters representing a valid parentheses string.
Example: Input: seq = '(())(())'
Constraints:
• 1 <= seq.size <= 10000
Output: The output is an array of length `seq.length`, where each element is 0 if the character at that index is part of subsequence A, and 1 if it is part of subsequence B.
Example: Output: [0, 1, 0, 0, 1, 1, 0, 1]
Constraints:
• The array should satisfy the condition that both subsequences are valid parentheses strings.
Goal: The goal is to split the given VPS string into two subsequences, A and B, while minimizing the maximum depth of the subsequences.
Steps:
• Initialize a variable `d` to track the current depth of parentheses.
• Iterate through the string and for each character, increment or decrement `d` based on whether the character is '(' or ')'.
• For each character, assign it to subsequence A (0) or B (1) based on the parity of the current depth.
• Return the array representing the split subsequences.
Goal: The input string will be a valid parentheses string of length between 1 and 10,000.
Steps:
• 1 <= seq.size <= 10000
• The input string contains only '(' and ')' characters.
Assumptions:
• The input string is guaranteed to be a valid parentheses string.
Input: Input: seq = '(())(())'
Explanation: The optimal split would be into subsequences A = '(())' and B = '(())', where the resulting depths are both 1. The answer array could be [0, 1, 0, 0, 1, 1, 0, 1].

Input: Input: seq = '(()())()'
Explanation: An optimal split would be into subsequences A = '(())' and B = '()()', where the depths are 1 and 1, respectively. The answer array could be [0, 1, 1, 0, 0, 1, 1, 1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus