FastPrepMinimum Binary Swaps to a Palindrome

Minimum Binary Swaps to a Palindrome

AT&T logoAT&T● MediumFULLTIMEOA

Problem statement

You may swap the bits at any two positions containing different bits in the binary string s. The positions do not need to be adjacent.

Return the minimum number of swaps needed to make s a palindrome. Return -1 if no sequence of swaps can do so.

Function

minPalindromeSwaps(s: String) → int

Examples

Example 1

s = "0100101"return = 2

Using zero-based indices, swap positions0 and1 to get1000101, then positions3 and4 to get1001001. The result is a palindrome. Initially three symmetric pairs mismatch; a swap can fix at most two, so one swap cannot suffice.

Example 2

s = "101000"return = 1

Swap positions0 and3 to get001100, which is a palindrome. The original string is not a palindrome, so one swap is minimal.

Constraints

  • 1 <= s.length <= 200000.
  • s contains only the characters 0 and 1.

More AT&T problems

See AT&T hiring insights
Saved
public int minPalindromeSwaps(String s) {
    // Write your solution here.
}
Checking account…