Can Make Palindrome from Substring - Problem

You are given a string s and array queries where queries[i] = [left_i, right_i, k_i]. We may rearrange the substring s[left_i...right_i] for each query and then choose up to k_i 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 i-th query queries[i].

Note: Each letter is counted individually for replacement, so if s[left_i...right_i] = "aaa" and k_i = 2, we can only replace two of the letters. Also, no query modifies the initial string s.

Input & Output

Example 1 — Multiple Query Types
$ 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]
💡 Note: Query [3,3,0]: substring "d" is already palindrome. Query [1,2,0]: "bc" needs 1 replacement, but k=0. Query [0,3,1]: "abcd" has 4 odd chars, needs 1.5≈2 replacements > k=1. Query [0,3,2]: "abcd" needs 2 replacements ≤ k=2. Query [0,4,1]: "abcda" has 2 odd chars (b,c), needs 0.5≈1 replacement ≤ k=1.
Example 2 — Edge Cases
$ Input: s = "lyb", queries = [[0,1,0],[2,2,1]]
Output: [false,true]
💡 Note: Query [0,1,0]: "ly" has 2 odd characters, needs 1 replacement but k=0. Query [2,2,1]: "b" is single character, always palindrome.
Example 3 — All Same Characters
$ Input: s = "aaaa", queries = [[0,3,0],[1,2,1]]
Output: [true,true]
💡 Note: Query [0,3,0]: "aaaa" has all even frequencies, palindrome possible. Query [1,2,1]: "aa" is already palindrome.

Constraints

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

Visualization

Tap to expand
Can Make Palindrome: Process OverviewInput:s = "abcda"queries = [[3,3,0], [1,2,0], [0,3,1]]Process Each Query1. Extract substring2. Count odd frequencies3. Check replacements ≤ kPalindrome Rule≤ 1 odd frequency charReplacements needed:max(0, (odds-1)/2)Examples"d" → 1 odd → 0 needed ✓"bc" → 2 odds → 1 needed"abcd" → 4 odds → 2 neededOutput: [true, false, false]Efficient solution uses prefix sums or bit manipulation
Understanding the Visualization
1
Input
String with query ranges and replacement limits
2
Process
Count odd-frequency characters in each substring
3
Output
Boolean array indicating palindrome possibility
Key Takeaway
🎯 Key Insight: A palindrome can have at most one character with odd frequency
Asked in
Google 25 Facebook 18 Amazon 12
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen