FastPrepMinimum Adjacent Swaps to Group Binary Values

Minimum Adjacent Swaps to Group Binary Values

Amazon logoAmazon● MediumNEW GRADFULLTIMEINTERNOAONSITE INTERVIEW

Problem statement

You are given a binary array bits. Using adjacent swaps, rearrange it so that equal values form two contiguous groups.

Either order is valid: all 0s before all 1s, or all 1s before all 0s. Return the minimum number of adjacent swaps over both orders.

Function

minimumAdjacentSwaps(bits: int[]) → long

Examples

Example 1

bits = [0,1,0,1]return = 1

Swap the middle 1 and 0 to obtain [0,0,1,1].

Example 2

bits = [1,1,0,0]return = 0

The array already has all ones before all zeroes.

Constraints

  • 1 <= bits.length <= 100000
  • Every value in bits is either 0 or 1.

More Amazon problems

See Amazon hiring insights
Saved
class Solution {
    public long minimumAdjacentSwaps(int[] bits) {
        // Write your code here
    }
}
Checking account…