FrontendInterviews.dev

Loading problem…

110. Valid Parentheses III - Check If String Can Be Valid

Hard•
Acceptance: 76.19%
•
🔓3/3 Pro unlocks today

This problem builds on valid-parentheses-ii. Complete that first, then load your solution to continue.

You're building an advanced code validator that needs to check if a string with locked and unlocked parentheses can be made valid by swapping unlocked parentheses.

Given a string s and a string locked, both of length n. s[i] is either '(' or ')', and locked[i] is either '0' or '1':

  • 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 sequence, otherwise return false.

Requirements

1. Basic Functionality

  • Check if string can be made valid
  • Some positions are locked (cannot change)
  • Some positions are unlocked (can swap)
  • Must form valid parentheses sequence

Example Usage

canBeValid("))()))", "010100");
// true
// Swap unlocked positions to get "()()()"

canBeValid("()()", "0000");
// true
// All positions unlocked, can rearrange to "()()"

canBeValid(")", "0");
// false
// Single ')' cannot be made valid

canBeValid("((()))", "111111");
// true
// All locked, already valid

Real-World Context

This problem models advanced code validation features:

  • Code formatters: Check if code can be fixed with limited changes
  • Text editors: Validate if text can be corrected
  • Parsers: Check if input can be made parseable
  • Linters: Determine if code can be auto-fixed

Constraints

  • n == s.length == locked.length
  • 1 <= n <= 10^5
  • s[i] is either '(' or ')'
  • locked[i] is either '0' or '1'
  • Must check if string can be made valid