class Solution:
def squareIsWhite(self, coordinates: str) -> bool:
# Column: 'a'..'h' maps to 1..8
col = ord(coordinates[0]) - ord('a') + 1
row = int(coordinates[1])
# If the sum is odd, square is black; if even, white
return (col + row) % 2 == 1
class Solution {
public:
bool squareIsWhite(string coordinates) {
int col = coordinates[0] - 'a' + 1;
int row = coordinates[1] - '0';
return (col + row) % 2 == 1;
}
};
class Solution {
public boolean squareIsWhite(String coordinates) {
int col = coordinates.charAt(0) - 'a' + 1;
int row = coordinates.charAt(1) - '0';
return (col + row) % 2 == 1;
}
}
var squareIsWhite = function(coordinates) {
const col = coordinates.charCodeAt(0) - 'a'.charCodeAt(0) + 1;
const row = Number(coordinates[1]);
return (col + row) % 2 === 1;
};
Given a string coordinates
representing the position of a square on a standard 8x8 chessboard (e.g., "a1"
, "h8"
), determine whether the square is white or black. The chessboard alternates colors, with the bottom-left square ("a1"
) always being black. The function should return true
if the square is white, and false
if it is black.
"a1"
, "c7"
, etc.).The problem is essentially about understanding the color pattern of a chessboard. Each square alternates color from its neighbors both horizontally and vertically. The key insight is that the color of any square depends on its row and column indices. Rather than simulating the whole board, we can use math to determine the color by analyzing the sum of the row and column numbers.
A brute-force approach could involve mapping out the entire chessboard and labeling each square, but this is unnecessary. Instead, we notice that if the sum of the row and column indices is even, the square is black; if odd, it's white. This observation lets us compute the answer in constant time.
true
for white and false
for black.This approach is efficient because it uses simple arithmetic operations and does not require any extra data structures.
Let's walk through the input "c7"
:
'c'
. 'c' - 'a' + 1 = 3
'7'
. row = 7
3 + 7 = 10
10 % 2 == 0
(even), so the square is black. false
.
Another example, "a2"
:
'a' - 'a' + 1 = 1
2
1 + 2 = 3
3 % 2 == 1
(odd), so the square is white. true
.
Brute-force approach:
If we mapped the color of every square on the chessboard, it would require O(1) time per query but O(64) space to store the board.
Optimized approach (our solution):
- Time Complexity: O(1), because we do a constant number of operations regardless of input.
- Space Complexity: O(1), since no extra data structures are used.
The key insight to this problem is that a chessboard's color pattern can be determined mathematically using the sum of the row and column indices. By converting the column letter to a number and adding it to the row, we can quickly check if the sum is even (black) or odd (white). This results in a highly efficient and elegant solution that avoids unnecessary computation or storage.