1016. Palindrome by Swaps

Hard7.5 points estimatedStringGreedyTwo Pointers3 hints

A sign painter has a row of lowercase letter tiles given by the string s. In one move the painter may swap two tiles that are next to each other. The painter wants the row to read the same from left to right and from right to left.

Return the minimum number of adjacent swaps needed to turn s into some palindrome, or -1 if no rearrangement of its letters can form a palindrome (more than one letter occurs an odd number of times). Any palindrome is acceptable, so the target is chosen to minimise the swaps. Aim for O(n log n) time and O(n) space.

Example 1

Input:
s = "xyzzxy"
Output:
1
Explanation:

Swapping the last two letters turns xyzzxy into xyzzyx, which reads the same backwards, so one swap is enough.

Example 2

Input:
s = "ab"
Output:
-1
Explanation:

Two letters that occur once each can never form a palindrome, so the answer is -1.

Constraints

1 ≤ n = s.length ≤ 20000

s consists of lowercase English letters only. The answer is at most about n^2 / 2 and fits in a 32-bit integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…