Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given a 0-indexed string array words having length n and containing 0-indexed strings.
You are allowed to perform the following operation any number of times (including zero):
i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length, 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y].Return an integer denoting the maximum number of palindromes words can contain, after performing some operations.
Note: i and j may be equal during an operation.
Example 1:
Input: words = ["abbb","ba","aa"] Output: 3 Explanation: In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"]. All strings in words are now palindromes. Hence, the maximum number of palindromes achievable is 3.
Example 2:
Input: words = ["abc","ab"] Output: 2 Explanation: In this example, one way to get the maximum number of palindromes is: Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"]. Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"]. Both strings are now palindromes. Hence, the maximum number of palindromes achievable is 2.
Example 3:
Input: words = ["cd","ef","a"] Output: 1 Explanation: In this example, there is no need to perform any operation. There is one palindrome in words "a". It can be shown that it is not possible to get more than one palindrome after any number of operations. Hence, the answer is 1.
Constraints:
1 <= words.length <= 10001 <= words[i].length <= 100words[i] consists only of lowercase English letters.Problem summary: You are given a 0-indexed string array words having length n and containing 0-indexed strings. You are allowed to perform the following operation any number of times (including zero): Choose integers i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length, 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y]. Return an integer denoting the maximum number of palindromes words can contain, after performing some operations. Note: i and j may be equal during an operation.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
["abbb","ba","aa"]
["abc","ab"]
["cd","ef","a"]
valid-palindrome)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
class Solution {
public int maxPalindromesAfterOperations(String[] words) {
int s = 0, mask = 0;
for (var w : words) {
s += w.length();
for (var c : w.toCharArray()) {
mask ^= 1 << (c - 'a');
}
}
s -= Integer.bitCount(mask);
Arrays.sort(words, (a, b) -> a.length() - b.length());
int ans = 0;
for (var w : words) {
s -= w.length() / 2 * 2;
if (s < 0) {
break;
}
++ans;
}
return ans;
}
}
// Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
func maxPalindromesAfterOperations(words []string) (ans int) {
var s, mask int
for _, w := range words {
s += len(w)
for _, c := range w {
mask ^= 1 << (c - 'a')
}
}
s -= bits.OnesCount(uint(mask))
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j])
})
for _, w := range words {
s -= len(w) / 2 * 2
if s < 0 {
break
}
ans++
}
return
}
# Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
class Solution:
def maxPalindromesAfterOperations(self, words: List[str]) -> int:
s = mask = 0
for w in words:
s += len(w)
for c in w:
mask ^= 1 << (ord(c) - ord("a"))
s -= mask.bit_count()
words.sort(key=len)
ans = 0
for w in words:
s -= len(w) // 2 * 2
if s < 0:
break
ans += 1
return ans
// Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
// class Solution {
// public int maxPalindromesAfterOperations(String[] words) {
// int s = 0, mask = 0;
// for (var w : words) {
// s += w.length();
// for (var c : w.toCharArray()) {
// mask ^= 1 << (c - 'a');
// }
// }
// s -= Integer.bitCount(mask);
// Arrays.sort(words, (a, b) -> a.length() - b.length());
// int ans = 0;
// for (var w : words) {
// s -= w.length() / 2 * 2;
// if (s < 0) {
// break;
// }
// ++ans;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3035: Maximum Palindromes After Operations
function maxPalindromesAfterOperations(words: string[]): number {
let s: number = 0;
let mask: number = 0;
for (const w of words) {
s += w.length;
for (const c of w) {
mask ^= 1 << (c.charCodeAt(0) - 'a'.charCodeAt(0));
}
}
s -= (mask.toString(2).match(/1/g) || []).length;
words.sort((a, b) => a.length - b.length);
let ans: number = 0;
for (const w of words) {
s -= Math.floor(w.length / 2) * 2;
if (s < 0) {
break;
}
ans++;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.