Skip to content

1812. Determine Color of a Chessboard Square

Description

You are given coordinates, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.

Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

 

Example 1:

Input: coordinates = "a1"
Output: false
Explanation: From the chessboard above, the square with coordinates "a1" is black, so return false.

Example 2:

Input: coordinates = "h3"
Output: true
Explanation: From the chessboard above, the square with coordinates "h3" is white, so return true.

Example 3:

Input: coordinates = "c7"
Output: false

 

Constraints:

  • coordinates.length == 2
  • 'a' <= coordinates[0] <= 'h'
  • '1' <= coordinates[1] <= '8'

Solutions

Solution 1: Pattern Recognition

Thinking

Squares alternate in color. Building the whole board for one query is unnecessary.

Adjacent squares have opposite colors, which is exactly the parity of the sum of the file and rank indices. Convert the letter and digit to integers and test whether their sum is odd (white) or even (black).

Observing the chessboard, we find that two squares \((x_1, y_1)\) and \((x_2, y_2)\) with the same color satisfy that both \(x_1 + y_1\) and \(x_2 + y_2\) are either odd or even.

Therefore, we can get the corresponding coordinates \((x, y)\) from \(\textit{coordinates}\). If \(x + y\) is odd, the square is white, and we return \(\textit{true}\); otherwise, we return \(\textit{false}\).

The time complexity is \(O(1)\), and the space complexity is \(O(1)\).

1
2
3
class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 1
1
2
3
4
5
class Solution {
    public boolean squareIsWhite(String coordinates) {
        return (coordinates.charAt(0) + coordinates.charAt(1)) % 2 == 1;
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool squareIsWhite(string coordinates) {
        return (coordinates[0] + coordinates[1]) % 2;
    }
};
1
2
3
func squareIsWhite(coordinates string) bool {
    return (coordinates[0]+coordinates[1])%2 == 1
}
1
2
3
function squareIsWhite(coordinates: string): boolean {
    return ((coordinates.charCodeAt(0) + coordinates.charCodeAt(1)) & 1) === 1;
}
1
2
3
4
5
6
impl Solution {
    pub fn square_is_white(coordinates: String) -> bool {
        let s = coordinates.as_bytes();
        ((s[0] + s[1]) & 1) == 1
    }
}
1
2
3
4
5
6
7
/**
 * @param {string} coordinates
 * @return {boolean}
 */
var squareIsWhite = function (coordinates) {
    return (coordinates[0].charCodeAt() + coordinates[1].charCodeAt()) % 2 == 1;
};
1
2
3
bool squareIsWhite(char* coordinates) {
    return (coordinates[0] + coordinates[1]) & 1;
}

Comments