← Snowflake Interview Insights
I got the feasibility check pretty fast (odd-length strings can have one character with an odd count, even-length need both even) but the minimum swap part is where I started fumbling.
First, check if a palindrome is possible by verifying that at most one character has an odd count. Then, use a two-pointer greedy strategy: fix the leftmost character by finding its matching counterpart from the right and swapping it into place, counting swaps; if no match exists (the odd character), swap it one step toward the center and continue. This yields the minimum number of adjacent swaps.
Pro tip: Emphasize that the greedy approach is optimal for two distinct characters because each swap fixes at least one character's final position, and the odd-count character (if any) must end up in the middle. Also, mention that the problem can be solved in O(n^2) time with O(1) extra space, which is acceptable for typical constraints.
Count the frequency of each character. If more than one character has an odd count, return -1 immediately.
Set left pointer to 0, right pointer to n-1, and swaps to 0. Convert the string to a mutable list for easy swapping.
While left < right, find the rightmost occurrence of the character at left within the range [left, right]. If found, swap it to the right position, incrementing swaps by the distance. If not found (this is the odd character), swap it one step toward the center and continue without moving the pointers.
After the loop, return the accumulated swaps as the minimum number of adjacent swaps needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.