Leetcode 1177: Can Make Palindrome from Substring

grid47
grid47
Exploring patterns and algorithms
Jul 12, 2024 5 min read

You are given a string s and an array of queries queries, where queries[i] = [lefti, righti, ki]. For each query, you can rearrange the substring s[lefti...righti] and replace up to ki characters in it with any lowercase English letters. Determine whether it is possible to form a palindrome from the resulting substring. Return an array of booleans answer where answer[i] is true if it is possible to form a palindrome for the i-th query, otherwise false.
Problem
Approach
Steps
Complexity
Input: The function receives a string `s` and an array `queries` as input.
Example: Input: s = 'abcbcba', queries = [[0, 6, 2], [1, 4, 1], [0, 2, 0], [3, 5, 1]]
Constraints:
• 1 <= s.length, queries.length <= 10^5
• 0 <= lefti <= righti < s.length
• 0 <= ki <= s.length
• s consists of lowercase English letters.
Output: The function returns a list of booleans indicating the result for each query.
Example: Output: [true, true, false, true]
Constraints:
• The output list must be of the same length as the input `queries`.
Goal: Check whether the substring defined by `lefti` and `righti` in each query can be rearranged and modified with up to `ki` character replacements to form a palindrome.
Steps:
• Calculate prefix bit masks to track character frequencies for the entire string.
• For each query, compute the XOR of prefix masks for the specified range to determine the odd-frequency characters.
• Count the number of odd-frequency characters and check if they can be adjusted to form a palindrome using up to `ki` replacements.
Goal: Ensure efficient handling of large inputs and fast computation for queries.
Steps:
• The solution should work in O(n + q) time, where `n` is the length of `s` and `q` is the number of queries.
• Minimize space usage by using prefix masks to represent character frequencies.
Assumptions:
• Each query operates independently without altering the input string `s`.
• Only lowercase English letters (26 characters) are considered.
Input: Input: s = 'aabbcc', queries = [[0, 5, 1], [0, 3, 0], [2, 4, 2]]
Explanation: Query 0: Substring 'aabbcc' can be rearranged to 'abcba' with 1 replacement. Query 1: Substring 'aabb' cannot be a palindrome without replacements. Query 2: Substring 'bbc' can be rearranged to 'cbc' with 2 replacements.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus