-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum Palindromes
More file actions
29 lines (28 loc) · 798 Bytes
/
Maximum Palindromes
File metadata and controls
29 lines (28 loc) · 798 Bytes
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
maximum = 26
def initialize(s):
global arr, fac, mod, M
M = 1000000007
n = len(s)
arr = [[0 for _ in range(n + 1)] for _ in range(maximum)]
for i in range(n):
for j in range(maximum):
arr[j][i + 1] = arr[j][i] + ((ord(s[i]) - 97) == j)
fac = [1] * (n + 1)
mod = [1] * (n + 1)
for i in range(1, n + 1):
fac[i] = (fac[i - 1] * i) % M
mod[i] = pow(fac[i], M - 2, M)
def answerQuery(l, r):
global arr, fac, mod, M
odd = 0
even = 0
divs = 1
for i in range(maximum):
value = arr[i][r] - arr[i][l - 1]
odd += (value & 1)
even += (value // 2)
divs = (divs * mod[value//2]) % M
result = (fac[even] * divs) % M
if (odd > 0):
result = (result * odd) % M
return result