FastPrepMinimum Swaps to Group Ones in a Square

Minimum Swaps to Group Ones in a Square

Amazon logoAmazon● MediumINTERNPHONE SCREEN
Learn

Problem statement

Given a square binary matrix grid, move all its ones into one contiguous, axis-aligned square using as few swaps as possible. There are exactly k * k ones for some positive integer k, so the destination square has side length k.

For this exercise, one swap exchanges the contents of any two cells; the cells need not be adjacent. Return the minimum number of swaps. The input always permits a k x k square within the matrix.

Function

minimumSquareGroupingSwaps(grid: int[][]) → int

Examples

Example 1

grid = [[1,0,0],[1,0,1],[0,1,0]]return = 2

The source example has four ones. The top-left 2 by 2 square already contains two, so two swaps bring the other ones inside.

Example 2

grid = [[1,1,0],[1,1,0],[0,0,0]]return = 0

All four ones already fill a contiguous square.

Example 3

grid = [[1,0,1],[0,0,0],[1,0,1]]return = 3

Every 2 by 2 square contains only one of the four corner ones.

Constraints

  • 1 <= grid.length <= 100; every row has the same length as the number of rows.
  • Every cell is 0 or 1.
  • The number of ones is a positive perfect square k * k, with 1 <= k <= grid.length.

More Amazon problems

See Amazon hiring insights
public int minimumSquareGroupingSwaps(int[][] grid) {
    // Write your code here
}
grid[[1,0,0],[1,0,1],[0,1,0]]
expected2
Checking account…