Leetcode 1812. Determine Color of a Chessboard Square
You are given a coordinate coordinates
in the form of a string that represents the position of a square on a standard 8x8 chessboard. The string will consist of two characters:
a
through h
).1
through 8
).You need to return a boolean value indicating whether the square is white or not. A white square on a standard chessboard alternates with black squares: starting from the bottom-left corner (a1), which is a black square.
coordinates
be invalid, or should we assume it is always valid as per the problem constraints?
true
for white and false
for black?
true
should be returned for a white square and false
for a black square.The chessboard’s alternating color pattern can be visualized with this insight:
a
to h
can be converted to a numerical index starting from 1 to 8.Here’s how we can implement this strategy:
public class Solution {
public boolean squareIsWhite(String coordinates) {
// Convert the column character to a number (a -> 1, b -> 2, ..., h -> 8)
int column = coordinates.charAt(0) - 'a' + 1;
// Convert the row character to a number (1 -> 1, 2 -> 2, ..., 8 -> 8)
int row = coordinates.charAt(1) - '0';
// Return true if the sum of column + row is odd (white), otherwise false (black)
return (column + row) % 2 != 0;
}
}
The solution has a constant time complexity since the operations performed (character conversion, addition, and modulo) all take constant time:
This solution efficiently determines the color of the chessboard square with minimal computational resources.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?