algoblazerEarly Access
LearnProblemsLeaderboard
Log inSign up

All problems

‹ Back to map
1 shown · 0/261 solved

Minimum Bracket Reversals to Balance

BronzeCommunity Beta
Asked atMicrosoft
Solve problem →
2000ms256MBAdded Aug 3, 2026

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.

Examples

Example 1

Input: s = ")("
Output: 2
Explanation: Both characters must flip: ")(" -> "()".

Example 2

Input: s = "(()("
Output: 1
Explanation: Flipping the last character gives "(())".

Example 3

Input: s = "((("
Output: -1
Explanation: A string of odd length can never be balanced.

Constraints

  • 1≤1 \leq1≤ s.length ≤105\leq 10^5≤105
  • s consists only of ( and ).

Details

Solved by6 people
Time limit2000ms
Memory256MB
AddedAug 3, 20265 weeks ago