FastPrepMinimum Swaps to Group Ones in a Square

Minimum Swaps to Group Ones in a Square

Amazon logoAmazon● MediumINTERNPHONE SCREEN

Updated

Problem statement

You are given a square grid grid where every cell holds a zero or a one. The number of ones is exactly k * k for some positive whole number k. Your goal is to gather all the ones into one solid square block of side k. The block must sit with its sides along the grid rows and columns.

One swap trades the contents of any two cells. The two cells do not have to be next to each other. Return the smallest number of swaps needed. A k x k square always fits inside the grid.

Function

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

Examples

Example 1

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

The grid has four ones, so the target is a 2 by 2 square. The best choice, such as the top-left square, already holds two ones, and no square holds more. Each swap moves one outside one in, so the answer is two.

Example 2

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

The four ones already fill the top-left square of side two. No swaps are needed, so the answer is zero.

Example 3

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

The four ones sit in the four corners. Every 2 by 2 square holds only one of them, so three ones must be swapped in. The answer is three.

Constraints

  • 1 <= grid.length <= 100.
  • Every row has as many cells as there are rows, so the grid is square.
  • Every cell is 0 or 1.
  • The number of ones is a positive perfect square k * k, with 1 <= k <= grid.length.

More Amazon Phone Screen questions

Similar questions at other companies

Amazon interview experiences

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