Can Make Palindrome from Substring — LeetCode 1177 Python Solution

MediumBit ManipulationArrayHash TableStringPrefix Sum
Problem
#1177
Pattern
Prefix Sum
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO((n + m) \times C)
SpaceO(n \times C) auxiliary

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

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) \times C).
What is the space complexity of LeetCode 1177. Can Make Palindrome from Substring?
The Python solution on this page uses O(n \times 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview