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

Difficulty: Easy


Problem Description

You are given two strings, coordinate1 and coordinate2, representing the coordinates of a square on an 8 x 8 chessboard. Return true if these two squares have the same color and false otherwise. The coordinate will always represent a valid chessboard square.


Key Insights

  • The chessboard alternates colors in a checkerboard pattern.
  • A square's color can be determined by its column and row.
  • The column is represented by a letter (a-h), and the row by a number (1-8).
  • Squares are black if the sum of the column index and row index is even; otherwise, they are white.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To determine if two squares have the same color, convert the column letter to a corresponding index (0 for 'a', 1 for 'b', ..., 7 for 'h') and convert the row number to an integer (1 to 8). Then, check if the sum of the row and column indices for both squares is even or odd. If both sums are even or both are odd, the squares have the same color.


Code Solutions

def squaresHaveSameColor(coordinate1: str, coordinate2: str) -> bool:
    # Convert column from letter to index (0 for 'a', 1 for 'b', ..., 7 for 'h')
    col1 = ord(coordinate1[0]) - ord('a')
    row1 = int(coordinate1[1]) - 1
    col2 = ord(coordinate2[0]) - ord('a')
    row2 = int(coordinate2[1]) - 1
    
    # Check if both squares have the same color
    return (col1 + row1) % 2 == (col2 + row2) % 2
← Back to All Questions