Taro Logo

Can Make Palindrome from Substring

Medium
Asked by:
Profile picture
31 views
Topics:
ArraysStringsBit Manipulation

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.

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 a boolean array answer where answer[i] is the result of the ith query queries[i].

Note that each letter is counted individually for replacement, so if, for example s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note that no query modifies the initial string s.

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.
queries[1]: substring = "bc", is not palidrome.
queries[2]: substring = "abcd", is not palidrome after replacing only 1 character.
queries[3]: 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[4]: substring = "abcda", could be changed to "abcba" which is palidrome.

Example 2:

Input: s = "lyb", queries = [[0,1,0],[2,2,1]]
Output: [false,true]

Constraints:

  • 1 <= s.length, queries.length <= 105
  • 0 <= lefti <= righti < s.length
  • 0 <= ki <= s.length
  • s consists of lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the characters in the string guaranteed to be lowercase English letters?
  2. Are the left and right bounds of each query inclusive, and are they always valid positions in the string?
  3. Can the replacement budget be zero, and should an already-palindromic slice still count as possible?
  4. When the problem says we may rearrange the slice, can the characters be placed in any order before the replacements?
  5. Should the result contain one yes-or-no answer per query, in the same order as the queries?

Brute Force Solution

Approach

Each question is answered on its own by inspecting that slice of the text from scratch. A slice can be rearranged into a palindrome when almost every letter appears an even number of times, and each replacement can repair two leftover odd letters.

Here's how the algorithm would work step-by-step:

  1. Take one question: a stretch of the text and a budget of replacements.
  2. Count how many times each letter appears inside that stretch.
  3. Count how many letters appear an odd number of times.
  4. A palindrome can leave at most one letter with an odd count, so every two leftover odd letters require one replacement.
  5. If that number of replacements fits in the budget, the answer is yes.
  6. Repeat for every question and keep the answers in the same order.

Code Implementation

class Solution:
    def canMakePaliQueries(self, input_string: str, queries: list[list[int]]) -> list[bool]:
        results_list = []

        # Process each query one by one as described by the brute force approach.
        for query in queries:
            start_index, end_index, max_changes_allowed = query
            substring = input_string[start_index : end_index + 1]

            character_counts = {}
            for character in substring:
                character_counts[character] = character_counts.get(character, 0) + 1

            odd_character_count = 0
            for count in character_counts.values():
                if count % 2 != 0:
                    odd_character_count += 1

            # A palindrome can have at most one character with an odd count.
            # The remaining odd-count characters must be paired up and changed.
            # Each change can fix two odd counts (e.g., change a 'c' to a 'd').
            changes_needed = odd_character_count // 2

            # Determine if the required changes are within the allowed budget for this query.
            results_list.append(changes_needed <= max_changes_allowed)

        return results_list

Big(O) Analysis

Time Complexity
O(q * n) – Each of the q queries can look at a slice as long as the whole text, which has length n. Counting the letters in a slice visits each of its characters once, and tallying the odd counts afterward is a small fixed amount of work. Across every query that is about q * n character visits, which simplifies to O(q * n).
Space Complexity
O(1) – While a query is being answered, the only extra memory is a tally of how often each letter appears. There are a fixed number of letters, so that tally does not grow with the text or the number of queries. The list of answers is the required output, and the auxiliary working memory stays constant.

Optimal Solution

Approach

Instead of recounting letters from scratch for every question, keep a running tally of how often each letter has appeared from the start of the text up to every position. Any stretch can then be measured by subtracting the tally from just before it from the tally at its end.

Here's how the algorithm would work step-by-step:

  1. Walk the text once and record, at every position, how many times each letter has appeared so far.
  2. For a question, subtract the tally from just before the stretch from the tally at the end of the stretch.
  3. That difference is the count of each letter inside the stretch.
  4. Count how many of those letters appear an odd number of times.
  5. Turn every two odd counts into one required replacement.
  6. Answer yes when the required replacements fit in the budget, and do this for every question.

Code Implementation

def can_make_palindrome_queries(input_string, queries):
    string_length = len(input_string)
    prefix_character_counts = [[0] * 26 for _ in range(string_length + 1)]

    # Pre-calculate a running tally of character frequencies to quickly find counts for any substring.
    for index, char in enumerate(input_string):
        for char_code in range(26):
            prefix_character_counts[index + 1][char_code] = prefix_character_counts[index][char_code]
        prefix_character_counts[index + 1][ord(char) - ord('a')] += 1

    results = []
    for start_index, end_index, allowed_changes in queries:
        odd_counts = 0
        for char_code in range(26):
            # Efficiently get character count for the specific substring using the pre-calculated tallies.
            count_at_end = prefix_character_counts[end_index + 1][char_code]
            count_before_start = prefix_character_counts[start_index][char_code]
            substring_char_count = count_at_end - count_before_start
            if substring_char_count % 2 != 0:
                odd_counts += 1

        # A palindrome can have at most one odd-count character. Each change can fix two odd counts.
        minimum_changes_needed = odd_counts // 2

        results.append(minimum_changes_needed <= allowed_changes)

    return results

Big(O) Analysis

Time Complexity
O(n + q) – Building the running tally walks the text of length n once and copies a fixed-size letter tally at each position. After that, each of the q queries inspects the fixed set of letter tallies with a subtraction, which does not depend on how long the slice is. The preparation is proportional to n and the questions are proportional to q, so the total is O(n + q).
Space Complexity
O(n) – The running tally keeps a fixed-size letter count at every position in the text, including one extra position before the first character. The number of stored rows therefore grows directly with the length of the text. That auxiliary table is the extra memory, so the space is O(n).

Edge Cases

No queries are given
How to Handle:
Return an empty list of answers, since there is nothing to decide.
The slice is a single character
How to Handle:
One character is already a palindrome, so the answer is yes even when the budget is zero.
The budget is zero and the slice is not a palindrome
How to Handle:
The answer is no when at least one replacement would be required.
Every character in the slice is the same
How to Handle:
All counts are even, or only one count is odd, so no replacements are required.
The budget is large enough to fix every odd count
How to Handle:
The answer is yes, because each replacement can repair two odd letter counts.
Several queries cover overlapping slices
How to Handle:
Each query is decided from its own slice, so overlapping ranges do not interfere with each other.