#1177

Can Make Palindrome from Substring

Medium
ArrayHash TableStringBit ManipulationPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal solution uses a prefix frequency array to efficiently calculate character frequencies for any substring in constant time. This reduces the need to repeatedly count characters, making the solution much faster.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a prefix frequency array where each entry at index i contains the frequency of each character from the start of the string up to index i.
  2. 2Step 2: For each query, use the prefix frequency array to quickly get the character frequencies for the substring defined by the query.
  3. 3Step 3: Count the number of characters with odd frequencies in the substring.
  4. 4Step 4: Determine if the number of odd frequencies is less than or equal to k (the number of allowed replacements).
solution.py16 lines
1def canMakePaliQueries(s, queries):
2    n = len(s)
3    prefix = [[0] * 26 for _ in range(n + 1)]
4    for i in range(n):
5        for j in range(26):
6            prefix[i + 1][j] = prefix[i][j]
7        prefix[i + 1][ord(s[i]) - ord('a')] += 1
8
9    result = []
10    for left, right, k in queries:
11        odd_count = 0
12        for j in range(26):
13            if (prefix[right + 1][j] - prefix[left][j]) % 2 != 0:
14                odd_count += 1
15        result.append(odd_count // 2 <= k)
16    return result

Complexity note: The time complexity is O(n + m), where n is the length of the string and m is the number of queries. The prefix frequency array allows us to compute character frequencies in constant time for each query.

  • 1Understanding character frequencies is crucial for determining palindrome possibilities.
  • 2Using prefix sums can significantly optimize the frequency counting process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.