Check if a Parentheses String Can Be Valid - Problem
A parentheses string is a non-empty string consisting only of '(' and ')'. It is valid if any of the following conditions is true:
- It is
(). - It can be written as
AB(A concatenated with B), where A and B are valid parentheses strings. - It can be written as
(A), where A is a valid parentheses string.
You are given a parentheses string s and a string locked, both of length n. locked is a binary string consisting only of '0's and '1's. For each index i of locked:
- If
locked[i]is'1', you cannot changes[i]. - If
locked[i]is'0', you can changes[i]to either'('or')'.
Return true if you can make s a valid parentheses string. Otherwise, return false.
Input & Output
Example 1 — Simple Valid Case
$
Input:
s = "))", locked = "00"
›
Output:
true
💡 Note:
Both positions are unlocked. We can change them to "()" to make a valid parentheses string.
Example 2 — Impossible Case
$
Input:
s = "())", locked = "000"
›
Output:
false
💡 Note:
String has odd length (3), so it's impossible to create a valid parentheses string.
Example 3 — Mixed Locked/Unlocked
$
Input:
s = "((((", locked = "1010"
›
Output:
true
💡 Note:
Positions 0,2 are locked as '('. Positions 1,3 are unlocked, we can set them to ')' to get "()()".
Constraints
- n == s.length == locked.length
- 1 ≤ n ≤ 105
- s[i] is either '(' or ')'
- locked[i] is either '0' or '1'
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
String with locked/unlocked positions marked
2
Greedy Assignment
Assign unlocked positions optimally
3
Validation
Check if result forms valid parentheses
Key Takeaway
🎯 Key Insight: Greedy assignment ensures we maintain proper balance while respecting locked constraints
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code