Fewest Adjacent Swaps to Turn a Device Label Into a Palindrome
Last updated: November 29, 2026
Quick Overview
A device label is a string that can be rearranged into a palindrome. Return the minimum number of swaps of adjacent characters needed to make it a palindrome.
0
0
0 solved
A device label is a string that can be rearranged into a palindrome. Return the minimum number of swaps of adjacent characters needed to make it a palindrome.
Google onsite interviewers use this to test greedy reasoning with a tricky middle-character case. They want the two-pointer outer-in strategy and an explanation for why fixing the leftmost character's partner first is optimal.
What the Interviewer Expects
- Work from the outside in with two pointers
- For the left character, find its nearest match from the right and bubble it outward
- Handle the single odd-count character by moving it one step toward the center
- Count swaps precisely
- State O(n^2) time and mention a BIT speedup
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Speed it up to O(n log n) with a Fenwick tree.
- Return -1 if no palindrome is possible.
- Swaps may be between any two positions, not only adjacent.
- Minimize swaps to make it a palindrome that is also lexicographically smallest.
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: string s guaranteed to be a palindrome permutation. Output: minimum adjacent swaps to make s a palindrome....
High-Level Design
Fix the outer pair first. Let l and r be the current ends. Search from r leftward for a character equal to s[l]. If found at k, bubble it right to r with r - k swaps, then shrink both en...