HardNo. 0782

Transform to Chessboard — LeetCode 782 Python Solution

Topics
Bit Manipulation, Array, Math, Matrix
Reading time
7 min

The problem

You are given an n x n binary grid board. In each move, you can swap any two rows with each other, or any two columns with each other.

Example

Input
board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
Output
2
Explanation
One potential sequence of moves is shown.

Python solution

PythonSolution
class Solution:
    def movesToChessboard(self, board: List[List[int]]) -> int:
        def f(mask, cnt):
            ones = mask.bit_count()
            if n & 1:
                if abs(n - 2 * ones) != 1 or abs(n - 2 * cnt) != 1:
                    return -1
                if ones == n // 2:
                    return n // 2 - (mask & 0xAAAAAAAA).bit_count()
                return (n + 1) // 2 - (mask & 0x55555555).bit_count()
            else:
                if ones != n // 2 or cnt != n // 2:
                    return -1
                cnt0 = n // 2 - (mask & 0xAAAAAAAA).bit_count()
                cnt1 = n // 2 - (mask & 0x55555555).bit_count()
                return min(cnt0, cnt1)

        n = len(board)
        mask = (1 << n) - 1
        rowMask = colMask = 0
        for i in range(n):
            rowMask |= board[0][i] << i
            colMask |= board[i][0] << i
        revRowMask = mask ^ rowMask
        revColMask = mask ^ colMask
        sameRow = sameCol = 0
        for i in range(n):
            curRowMask = curColMask = 0
            for j in range(n):
                curRowMask |= board[i][j] << j
                curColMask |= board[j][i] << j
            if curRowMask not in (rowMask, revRowMask) or curColMask not in (
                colMask,
                revColMask,
            ):
                return -1
            sameRow += curRowMask == rowMask
            sameCol += curColMask == colMask
        t1 = f(rowMask, sameRow)
        t2 = f(colMask, sameCol)
        return -1 if t1 == -1 or t2 == -1 else t1 + t2

Complexity

Time
O(n2)where n is the size of the chessboard
Space · auxiliary
O(1)

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 782. Transform to Chessboard is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 782. Transform to Chessboard?

LeetCode 782. Transform to Chessboard is rated Hard on LeetCode.

What is the time complexity of LeetCode 782. Transform to Chessboard?

The Python solution on this page runs in O(n2), where n is the size of the chessboard.

What is the space complexity of LeetCode 782. Transform to Chessboard?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 782. Transform to Chessboard cover?

LeetCode 782. Transform to Chessboard is tagged Bit Manipulation, Array, Math and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.