Back to blog
Sep 26, 2024
5 min read

Check if Two Chessboard Squares Have the Same Color

Determine if two given chessboard squares have the same color based on their coordinates.

Difficulty: Easy | Acceptance: 72.30% | Paid: No Topics: Math, String

You are given two strings, coordinate1 and coordinate2, representing the coordinates of two squares on a chessboard.

A chessboard has 8 rows (ranks) and 8 columns (files). The rows are labeled from 1 to 8, and the columns are labeled from ‘a’ to ‘h’.

The color of a square is determined by the following rules:

  • If the sum of the row number and the column number (where ‘a’ = 1, ‘b’ = 2, …, ‘h’ = 8) is even, the square is white.
  • If the sum is odd, the square is black.

Return true if the two squares have the same color, and false otherwise.

Examples

Example 1

Input: coordinate1 = "a1", coordinate2 = "c3"
Output: true
Explanation:
Square "a1" is black, and square "c3" is also black.

Example 2

Input: coordinate1 = "a1", coordinate2 = "h3"
Output: false
Explanation:
Square "a1" is black, while square "h3" is white.

Constraints

coordinate1.length == coordinate2.length == 2
'a' <= coordinate1[0], coordinate2[0] <= 'h'
'1' <= coordinate1[1], coordinate2[1] <= '8'

Explicit Index Conversion

Intuition Convert the letter to a column index (0-7) and the number to a row index (0-7), then check if the parity of their sum is the same for both squares.

Steps

  • Extract the column letter and row number from each coordinate
  • Convert the letter to a 0-based index (a=0, b=1, etc.)
  • Convert the number to a 0-based index (1=0, 2=1, etc.)
  • Check if (row + col) % 2 is equal for both squares
python
class Solution:
    def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
        def get_color(coord):
            col = ord(coord[0]) - ord('a')
            row = int(coord[1]) - 1
            return (row + col) % 2
        
        return get_color(coordinate1) == get_color(coordinate2)

Complexity

  • Time: O(1) - Constant time operations
  • Space: O(1) - No extra space used
  • Notes: Clear and readable approach with explicit conversion

Direct ASCII Sum

Intuition Use ASCII values directly without explicit index conversion. The parity of (ASCII value of letter + ASCII value of digit) determines the color.

Steps

  • Sum the ASCII value of the letter and the ASCII value of the digit for each coordinate
  • Check if the parity of these sums is the same
python
class Solution:
    def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
        return (ord(coordinate1[0]) + ord(coordinate1[1])) % 2 == (ord(coordinate2[0]) + ord(coordinate2[1])) % 2

Complexity

  • Time: O(1) - Constant time operations
  • Space: O(1) - No extra space used
  • Notes: More concise but slightly less readable