Watch 10 video solutions for Transform to Chessboard, a hard level problem involving Array, Math, Bit Manipulation. This walkthrough by Coding Decoded has 3,028 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return -1.
A chessboard board is a board where no 0's and no 1's are 4-directionally adjacent.
Example 1:
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. The first move swaps the first and second column. The second move swaps the second and third row.
Example 2:
Input: board = [[0,1],[1,0]] Output: 0 Explanation: Also note that the board with 0 in the top left corner, is also a valid chessboard.
Example 3:
Input: board = [[1,0],[1,0]] Output: -1 Explanation: No matter what sequence of moves you make, you cannot end with a valid chessboard.
Constraints:
n == board.lengthn == board[i].length2 <= n <= 30board[i][j] is either 0 or 1.Problem Overview: You are given an n x n binary matrix. The task is to transform it into a valid chessboard pattern (alternating 0s and 1s in rows and columns) using the minimum number of row or column swaps. If the transformation is impossible, return -1.
Approach 1: Pattern Matching and Position Swapping (O(n^2) time, O(1) space)
A valid chessboard has exactly two types of rows and two types of columns, and they must be bitwise inverses of each other. Start by comparing every row with the first row and every column with the first column. Any row must either match the first row or be its inverse; otherwise the configuration cannot become a chessboard. After validating this constraint, count how many rows and columns are misplaced relative to the expected alternating pattern. The minimum swaps are determined by comparing the matrix with two possible chessboard patterns (starting with 0 or starting with 1). Implementation often uses bit masks or parity checks to count mismatches efficiently. This approach works directly on the array representation of the matrix and runs in O(n^2) because every cell is inspected once.
Approach 2: Recursive Approach with Memoization (O(n^2) time, O(n^2) space)
This approach treats the board transformation as a recursive state exploration problem. At each step, you attempt swapping rows or columns that violate the chessboard pattern. The recursion evaluates whether the current configuration can reach a valid state with minimal operations. Memoization stores previously computed board states (often serialized as bit patterns) to avoid recomputation. Although recursion introduces overhead, caching ensures the algorithm does not repeatedly explore identical states. This strategy highlights the structural constraints of alternating patterns and demonstrates how bit manipulation can encode rows and columns compactly for memo keys.
Approach 3: Iterative Approach with Tabulation (O(n^2) time, O(n) space)
The tabulation method computes valid row and column placements iteratively. Instead of recursion, it counts the number of 1s in rows and columns and verifies that counts differ by at most one, which is required for alternating patterns. Then it iterates through indices and calculates how many positions violate the expected parity pattern ((i + j) % 2). Using these mismatch counts, the algorithm derives the minimal swaps required for rows and columns separately. This method avoids recursion overhead and keeps memory usage small while still leveraging the structure of alternating grids. It is easier to implement in iterative languages and works well when you want deterministic state progression.
Recommended for interviews: The pattern matching and position swapping approach is the standard solution interviewers expect. It shows you understand the mathematical constraints of chessboard patterns and can derive swap counts using parity checks. Recursive exploration demonstrates reasoning about state transitions, but the optimal solution proves stronger algorithmic insight and runs with minimal space.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Pattern Matching and Position Swapping | O(n^2) | O(1) | Best general solution. Efficiently validates row/column patterns and computes minimal swaps. |
| Recursive Approach with Memoization | O(n^2) | O(n^2) | Useful for understanding state transitions and exploring swap combinations. |
| Iterative Approach with Tabulation | O(n^2) | O(n) | Preferred when avoiding recursion and computing mismatch counts iteratively. |