All problems

Problem 326

Minimum Swaps to Balance Brackets

Medium · 20 pts · String, Greedy, Stack

Problem

A string has equal numbers of '[' and ']' brackets, but they may be in the wrong order. In one move you may swap the brackets at any two positions (they do not need to be next to each other). Find the minimum number of swaps needed to make the string balanced, meaning every '[' is closed by a later ']'.

Input

A single string S of '[' and ']' with equal counts of each.

Output

Print the minimum number of swaps.

Constraints

2 <= |S| <= 1000000; |S| is even

Example input

][][

Example output

1

Explanation

In '][][' swapping the first and last characters gives '[[]]', which is balanced, so one swap is enough.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Valid Parentheses with Wildcards Next: Reverse Each Word