# 1177. Can Make Palindrome from Substring(Prefix Sum)

Given a string s, we make queries on substrings of s.

For each query queries[i] = [left, right, k], we may rearrange the substring s[left], ..., s[right], and then choose up to k of them to replace with any lowercase English letter.

If the substring is possible to be a palindrome string after the operations above, the result of the query is true. Otherwise, the result is false.

Return an array answer[], where answer[i] is the result of the i-th query queries[i].

Note that: Each letter is counted individually for replacement so if for example s[left..right] = "aaa", and k = 2, we can only replace two of the letters. (Also, note that the initial string s is never modified by any query.)

Example :

Input: s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
Output: [true,false,false,true,true]
Explanation:
queries : substring = "d", is palidrome.
queries : substring = "bc", is not palidrome.
queries : substring = "abcd", is not palidrome after replacing only 1 character.
queries : substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab".
queries : substring = "abcda", could be changed to "abcba" which is palidrome.

Constraints:

1 <= s.length, queries.length <= 105
0 <= queries[i] <= queries[i] < s.length
0 <= queries[i] <= s.length
s only contains lowercase English letters.

## Solution

Careful for rearranging，not just replacing
applied prefix sum, which can reduce the time complexity

O(N * 26) O(N)

## Code

``````class Solution {
public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
List<Boolean> res = new ArrayList<>();
int[][] count = new int[s.length() + 1];
for(int i = 0;i < s.length();i++){
count[i+1] = count[i].clone();
++count[i+1][s.charAt(i) - 'a'];
}
for(int[] query : queries){
int singleNum = 0;
for(int i = 0; i < 26;i++){
singleNum += (count[query + 1][i] - count[query][i]) % 2;
}
res.add((singleNum / 2) <= query ? true : false);
}
return res;
}
}
``````