We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if Two Chessboard Squares Have the Same Color

Number: 3553

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given two chessboard square coordinates (like "a1" or "h3") from an 8x8 chessboard, determine if they are of the same color. The chessboard alternates colors, and the coordinate consists of a letter (column) and a digit (row).


Key Insights

  • Each square's color can be determined by the parity (odd/even) of the sum of its column index and row number.
  • Column letters ('a' to 'h') are mapped to numbers (1 to 8). Adding this to the row digit gives a sum; even sums correspond to one color, odd sums to the opposite.
  • No additional data structures are required; only arithmetic operations are used.

Space and Time Complexity

Time Complexity: O(1) - Only constant time arithmetic operations are performed. Space Complexity: O(1) - Only a few integer variables are used.


Solution

We convert the column, represented by a letter, to a numeric index by subtracting the ASCII value of 'a' and adding 1. We convert the row character to an integer. By summing these values and taking the result modulo 2, we can determine the square's color. Two squares have the same color if their corresponding modulo results are equal. This approach efficiently checks the parity of the sum for both coordinates.


Code Solutions

# Function to determine if two chessboard squares have the same color
def square_is_same_color(coordinate1, coordinate2):
    # Convert the column letter to number (a -> 1, b -> 2, ..., h -> 8)
    col1 = ord(coordinate1[0]) - ord('a') + 1
    # Convert row character to integer
    row1 = int(coordinate1[1])
    
    col2 = ord(coordinate2[0]) - ord('a') + 1
    row2 = int(coordinate2[1])
    
    # Determine color parity for both squares
    # A square is one color if (column + row) % 2 is 0, and the other color if it's 1.
    return (col1 + row1) % 2 == (col2 + row2) % 2

# Example usage:
print(square_is_same_color("a1", "c3"))  # Expected output: True
print(square_is_same_color("a1", "h3"))  # Expected output: False
← Back to All Questions