1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
s = input()

from collections import Counter
counter = Counter(s)
odd_vals = [v for v in counter.values() if v % 2 == 1]
if len(odd_vals) > 1:
    print("-1")
else:
    def get(s):
        if len(s) <= 2:
            return 0
    
        if s[0] == s[-1]:
            return get(s[1:-1])
        else:
            i = 0
            j = len(s) - 1
    
            seen_i = {}
            seen_j = {}
    
            while i < len(s) and j >= 0:
    
                if s[i] not in seen_i:
                    seen_i[s[i]] = i
                if s[j] not in seen_j:
                    seen_j[s[j]] = j
    
                if s[i] in seen_j:
                    to_swap_i = i
                    to_swap_j = seen_j[s[i]]
                    swap_cost = to_swap_i + (len(s) - 1 - to_swap_j)
    
                if s[j] in seen_i:
                    to_swap_i_ = seen_i[s[j]]
                    to_swap_j_ = j
                    swap_cost_ = to_swap_i_ + (len(s) - 1 - to_swap_j_)
                    if s[i] not in seen_j or swap_cost_ < swap_cost:
                        to_swap_i = to_swap_i_
                        to_swap_j = to_swap_j_
                        swap_cost = swap_cost_
    
                if s[i] in seen_j or s[j] in seen_i:
                    if to_swap_i == to_swap_j:
                        i += 1
                        j -= 1
                        continue
    
                    return swap_cost + get(
                        s[:to_swap_i] + s[to_swap_i + 1:to_swap_j] + s[
                                                                     to_swap_j + 1:])
    
                i += 1
                j -= 1
    
    print(get(s))