Check if a Parentheses String Can Be Valid - Problem
๐ Unlock the Valid Parentheses
Imagine you have a string of parentheses where some positions are locked and cannot be changed, while others are flexible and can be modified to either '(' or ')'.
Your challenge is to determine if you can manipulate the flexible positions to create a perfectly balanced parentheses string. A valid parentheses string follows these rules:
- It equals
"()", or - It can be formed by concatenating two valid strings:
AB, or - It can be formed by wrapping a valid string:
(A)
Input: Two strings of equal length n:
s- the parentheses string containing only'('and')'locked- a binary string where'1'means position is locked,'0'means flexible
Output: Return true if you can make s valid by changing flexible positions, false otherwise.
Example: s = ")())", locked = "0100" โ We can change the first ')' to '(' to get "(())", which is valid!
Input & Output
example_1.py โ Basic Valid Case
$
Input:
s = ")())", locked = "0100"
โบ
Output:
true
๐ก Note:
We can change s[0] from ')' to '(' since locked[0] = '0'. This gives us "(())" which is valid: it can be written as (()) where the inner content is ().
example_2.py โ All Flexible
$
Input:
s = "((((", locked = "0000"
โบ
Output:
true
๐ก Note:
All positions are flexible. We can change this to "(())" or "()()" or any other valid combination. For example: change positions 2,3 to ')' to get "(())".
example_3.py โ Impossible Case
$
Input:
s = "())", locked = "000"
โบ
Output:
false
๐ก Note:
The string has odd length (3), so it's impossible to create a valid parentheses string since valid strings must have even length (equal numbers of '(' and ')').
Visualization
Tap to expand
Understanding the Visualization
1
Identify Gate Types
Some gates are broken (locked) and can't change, others are flexible and can be set to entry or exit
2
Left Flow Check
Ensure at no point do we have more cars exiting than have entered (negative count)
3
Right Flow Check
Working backwards, ensure we can balance all cars by setting flexible gates optimally
4
Final Validation
If both flow checks pass, we can create a valid configuration
Key Takeaway
๐ฏ Key Insight: We don't need to assign exact values to flexible positions - we just need to prove that a valid assignment exists by ensuring flow constraints are never violated.
Time & Space Complexity
Time Complexity
O(n)
Two linear passes through the string
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track counts
โ Linear Space
Constraints
- n == s.length == locked.length
- 1 โค n โค 105
- s[i] is either '(' or ')'
- locked[i] is either '0' or '1'
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code