Leetcode 2116: Check if a Parentheses String Can Be Valid

grid47
grid47
Exploring patterns and algorithms
Apr 9, 2024 7 min read

You are given a string s consisting of parentheses ‘(’ and ‘)’, and a binary string locked of the same length. Each position in locked determines whether the corresponding character in s can be changed or not. If locked[i] is ‘1’, the character s[i] cannot be modified, but if locked[i] is ‘0’, you can change s[i] to either ‘(’ or ‘)’. Your task is to determine if it is possible to make the string s a valid parentheses string by changing the positions where locked[i] is ‘0’. A valid parentheses string is defined by the following conditions: It is either ‘()’, or a concatenation of valid parentheses strings, or it can be written as (A) where A is a valid parentheses string.
Problem
Approach
Steps
Complexity
Input: You are given a string s representing the parentheses and a binary string locked representing which characters can be modified.
Example: s = ')())(', locked = '01001'
Constraints:
• 1 <= n <= 10^5
• s consists of '(' and ')'.
• locked consists of '0' and '1'.
Output: Return true if it is possible to make s a valid parentheses string by modifying the characters that correspond to '0' in locked. Otherwise, return false.
Example: For s = ')())(', locked = '01001', the output is true.
Constraints:
Goal: To determine if it's possible to modify certain characters in s to make it a valid parentheses string.
Steps:
• Check if the string length is even, as a valid parentheses string must have an even number of characters.
• Use a helper function to check the string from left to right, counting the open and closed parentheses while considering the positions where characters can be modified (i.e., where locked[i] = '0').
• Use another helper function to check the string from right to left to ensure the string can be balanced correctly from both directions.
Goal: Ensure that the solution works efficiently for large inputs.
Steps:
• The length of s and locked is at most 10^5.
Assumptions:
• The input strings s and locked are non-empty.
• Each character in s is either '(' or ')'.
• Each character in locked is either '0' or '1'.
Input: Example 1: s = ')())(', locked = '01001'
Explanation: In this example, we can change the characters at positions 1, 4, and 5 to balance the parentheses, resulting in a valid string. The output is true.

Input: Example 2: s = '(()', locked = '010'
Explanation: In this case, no modification can balance the parentheses, so the output is false.

Link to LeetCode Lab


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