cswork / OAOpen practice workspace

MicrosoftOA #10

Balance the Game Board

Estimated MediumJudge-ready

Topics (AI-labelled)SimulationPrefix & Ranges

A token sits at one of the positions 0..N, and the letters lie between adjacent positions. Each step flips the a/b letter the token crosses. Find the minimum number of steps needed to make the counts of the two letters equal, or −1 if it is impossible.

Input

The first line contains the letter string L (1..100, only a/b), and the second line contains start (0..N).

Output

Output a single integer, the answer.

Example 1

Input:

aaabab
0

Output:

1

Example 2

Input:

aaabab
6

Output:

5

Example 3

Input:

ababa
1

Output:

-1

Example notes

Example 1: moving right across the first a turns the string into baabab, with 3 of each letter; the answer is 1.

Example 2: moving left 5 steps flips indices 1..5, giving abbaba with 3 of each letter; no shorter move balances the letters, so the answer is 5.

Example 3: the total number of letters, 5, is odd, so they cannot be split into equal counts; output −1.

Editorial

Loading solution…