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 change s[i].
  • If locked[i] is '0', you can change s[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
Check if Parentheses String Can Be Valid INPUT String s: ) ) idx 0 idx 1 String locked: 0 0 unlocked unlocked 0 = Can change 1 = Fixed n = 2 (even length) ALGORITHM STEPS 1 Check Length n=2 is even [OK] 2 Left-to-Right Pass Track open balance idx 0: ')' unlocked --> treat as '(' bal=1 idx 1: ')' unlocked 3 Right-to-Left Pass Track close balance idx 1: ')' unlocked --> treat as ')' bal=1 idx 0: ')' unlocked 4 Both Passes Valid Balance never negative Return: true FINAL RESULT Valid Transformation: Before: ) ) After: ( ) Output: true "()" is valid! Key Insight: The greedy two-pass approach works because unlocked positions can flexibly become '(' or ')'. Left pass ensures enough '(' to match ')'. Right pass ensures enough ')' to match '('. If both passes succeed without balance going negative, valid pairing exists. Time: O(n), Space: O(1) TutorialsPoint - Check if a Parentheses String Can Be Valid | Greedy Two-Pass Strategy
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen