Loading...
You are given a string s consisting only of the characters ( and ).
In one reversal you may flip any single character: ( becomes ) or ) becomes (.
Return the minimum number of reversals needed to make s balanced (every opening bracket has a matching closing bracket after it, in the usual sense). If s is already balanced, return 0. If it is impossible to balance, which happens exactly when the length of s is odd, return -1.
Input: s = ")("
Output: 2
Explanation: Both characters must flip: ")(" -> "()".
Input: s = "(()("
Output: 1
Explanation: Flipping the last character gives "(())".
Input: s = "((("
Output: -1
Explanation: A string of odd length can never be balanced.
s.length ≤105s consists only of ( and ).Click "Run" to test with sample cases or "Submit" to run all tests.