algoadvance

You are given a string coordinates that represents the coordinates of a square of the chessboard. Below are some points for better understanding:

  1. The coordinate will be in the format of "<letter><digit>", where <letter> is a letter from a to h representing the column and <digit> is a digit from 1 to 8 representing the row of the chessboard.

Your task is to determine whether the square is white or black.

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

A chessboard is colored in an alternating pattern. Specifically:

Clarifying Questions

  1. Should we assume that the given input will always be valid and in the expected format?
    • Yes, the input can be assumed to be always a valid coordinate in the form required.
  2. What should the function return if the square is black?
    • The function should return false if the square is black.
  3. What should the function return if the square is white?
    • The function should return true if the square is white.

Strategy

The strategy to solve this problem involves:

  1. Parsing the input string to separate the column letter and the row digit.
  2. Converting the column letter to an integer by considering its position in the alphabet.
  3. Checking the parity (odd/even) of both the column and the row.
  4. Determining the color based on the parity:
    • Both the column position and the row number starting from an odd number will be one color (e.g., black).
    • If one is odd and the other is even, it will be the opposite color (e.g., white).

The pattern can be summarized as:

Code

def squareIsWhite(coordinates: str) -> bool:
    column = coordinates[0]
    row = coordinates[1]
    
    # Convert column from a-h to 1-8
    column_number = ord(column) - ord('a') + 1
    row_number = int(row)
    
    # Check the parity
    return (column_number + row_number) % 2 != 0

# Example Usage:
coordinates = "a1"
print(squareIsWhite(coordinates))  # Output: False (Black square)

Time Complexity

The time complexity of this solution is O(1) since we perform a fixed number of operations regardless of the input size.

Try our interview co-pilot at AlgoAdvance.com