MediumNo. 1177
Can Make Palindrome from Substring — LeetCode 1177 Python Solution
- Pattern
- Prefix Sum
- Topics
- Bit Manipulation, Array, Hash Table, String, Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may rearrange the substring s[lefti...righti] for each query and then choose up to ki of them to replace with any lowercase English letter.
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[0]: substring = "d", is palidrome.
Python solution
class Solution:
def canMakePaliQueries(self, s: str, queries: List[List[int]]) -> List[bool]:
n = len(s)
ss = [[0] * 26 for _ in range(n + 1)]
for i, c in enumerate(s, 1):
ss[i] = ss[i - 1][:]
ss[i][ord(c) - ord("a")] += 1
ans = []
for l, r, k in queries:
cnt = sum((ss[r + 1][j] - ss[l][j]) & 1 for j in range(26))
ans.append(cnt // 2 <= k)
return ansComplexity
- Time
- O((n + m) × C)
- Space · auxiliary
- O(n × C)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1177. Can Make Palindrome from Substring is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1178 | Number of Valid Words for Each Puzzle | Hard |
| 0691 | Stickers to Spell Word | Hard |
| 1255 | Maximum Score Words Formed by Letters | Hard |
| 1371 | Find the Longest Substring Containing Vowels in Even Counts | Medium |
| 1442 | Count Triplets That Can Form Two Arrays of Equal XOR | Medium |
| 1684 | Count the Number of Consistent Strings | Easy |
Frequently asked questions
- How hard is LeetCode 1177. Can Make Palindrome from Substring?
LeetCode 1177. Can Make Palindrome from Substring is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1177. Can Make Palindrome from Substring?
The Python solution on this page runs in O((n + m) × C).
- What is the space complexity of LeetCode 1177. Can Make Palindrome from Substring?
The Python solution on this page uses O(n × C) auxiliary space.
- What topics does LeetCode 1177. Can Make Palindrome from Substring cover?
LeetCode 1177. Can Make Palindrome from Substring is tagged Bit Manipulation, Array, Hash Table, String and Prefix Sum on LeetCode.