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

Determine Color of a Chessboard Square

Number: 1920

Difficulty: Easy

Paid? No

Companies: J.P. Morgan


Problem Description

Given a string representing the chessboard coordinates (e.g., "a1", "h3", "c7"), determine whether the corresponding square on a chessboard is white or black. Return true if the square is white, and false if it is black.


Key Insights

  • Convert the letter coordinate to a numerical value (e.g., 'a' -> 1, 'b' -> 2, …, 'h' -> 8).
  • Add the numerical representation of the letter coordinate to the numeric digit from the coordinate.
  • If the resulting sum is even, the square is black; if odd, the square is white.
  • This mapping works because the chessboard alternates colors in a predictable pattern.

Space and Time Complexity

Time Complexity: O(1) – The solution performs a fixed number of operations regardless of input. Space Complexity: O(1) – Only a few extra variables are used.


Solution

The approach involves converting the letter in the input coordinate to a number. This is done by taking the ASCII value of the character and subtracting the ASCII value of 'a' then adding 1. Next, convert the numerical character directly to an integer. Sum these two numbers. Since squares are colored alternately, an even sum indicates a black square and an odd sum indicates a white square. This simple arithmetic check is both sufficient and efficient for solving the problem.


Code Solutions

# Function to determine the color of a chessboard square.
def squareIsWhite(coordinates: str) -> bool:
    # Convert the letter to a number (a -> 1, b -> 2, ..., h -> 8)
    letter_value = ord(coordinates[0]) - ord('a') + 1
    # Convert the digit from string to integer.
    digit_value = int(coordinates[1])
    # If the sum of letter_value and digit_value is odd, it's a white square.
    return (letter_value + digit_value) % 2 == 1

# Example usage:
print(squareIsWhite("a1"))  # Expected output: False (black square)
print(squareIsWhite("h3"))  # Expected output: True (white square)
print(squareIsWhite("c7"))  # Expected output: False (black square)
← Back to All Questions