cswork / OAOpen practice workspace

AmazonOA #306

Minimum Swaps to Make Palindrome

Estimated MediumJudge-ready

Topics (AI-labelled)StringsGreedy

You are given a string s consisting only of the characters 0 and 1. In each operation you may swap the characters at any two positions i and j (they do not need to be adjacent). Find the minimum number of swaps needed to turn s into a palindrome; if it cannot be done, output −1.

A palindrome reads the same forward and backward. For example, "0", "111", "010" and "10101" are palindromes, while "001", "10" and "11101" are not.

Input

One line containing a 01 string s. 1≤length of s≤10^6.

Output

Output a single integer, the minimum number of swaps, or −1 if there is no solution.

Example 1

Input:

0100101

Output:

2

Example 2

Input:

10

Output:

-1

Example 3

Input:

0011

Output:

1

Example notes

Example 1: s="0100101" (1-indexed). Swapping (4,5) gives "0101001", and then swapping (1,2) gives "1001001", for 2 swaps in total; one swap is not enough, so the answer is 2. Example 2: "10" has only one 1, and an even-length palindrome needs an even number of 1s, so the answer is −1. Example 3: swapping the 1st and 3rd characters of "0011" gives "1001" in a single swap, so the answer is 1.

Editorial

Loading solution…