#782
Transform to Chessboard
HardArrayMathBit ManipulationMatrixArrayMatrix
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of a chessboard pattern and uses counting to determine how many swaps are necessary. By checking the counts of 0's and 1's and their positions, we can efficiently compute the minimum swaps required without generating all configurations.
⚙️
Algorithm
4 steps- 1Step 1: Count the number of 1's in the first row and first column to determine the expected pattern.
- 2Step 2: Validate that the number of 1's and 0's are appropriate for a chessboard configuration.
- 3Step 3: Count the number of row and column mismatches against the expected pattern.
- 4Step 4: Return the minimum number of swaps needed based on the mismatches.
solution.py20 lines
1# Full working Python code
2
3def minSwapsToChessboard(board):
4 n = len(board)
5 rowCount = [0] * n
6 colCount = [0] * n
7 for i in range(n):
8 for j in range(n):
9 if board[i][j] == 1:
10 rowCount[i] += 1
11 colCount[j] += 1
12 if not (n // 2 <= rowCount[0] <= (n + 1) // 2) or not (n // 2 <= colCount[0] <= (n + 1) // 2):
13 return -1
14 rowSwaps = colSwaps = 0
15 for i in range(n):
16 if (board[i][0] == 1) != (i % 2):
17 rowSwaps += 1
18 if (board[0][i] == 1) != (i % 2):
19 colSwaps += 1
20 return (rowSwaps + colSwaps) // 2ℹ
Complexity note: This complexity is achieved because we only need to iterate through the board a limited number of times, specifically to count and validate the rows and columns.
- 1A valid chessboard must have an equal number of 0's and 1's, or differ by one.
- 2The first row and column define the expected pattern for the rest of the board.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.