algoadvance

Leetcode 1812. Determine Color of a Chessboard Square

Problem Statement

You are given a coordinate coordinates that represents the position of a square on a standard 8x8 chessboard. Chessboard squares are identified by a letter and a number, where the letter represents the column (‘a’ to ‘h’) and the number represents the row (1 to 8).

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

For example:

Clarifying Questions

  1. Can coordinates be outside the scope of the chessboard dimensions (a-h) and (1-8)?
    • No, coordinates will always be valid and within the chessboard dimensions.
  2. Should the function be case-sensitive regarding the input coordinate (e.g., ‘A1’ vs ‘a1’)?
    • The problem assumes that the input is always lowercase and correctly formatted.

Strategy

To determine the color of the chessboard square:

  1. Convert the column letter to a number (a to h translates to 1 to 8).
  2. Use the row number directly since it is already in numeral form.
  3. If the sum of the column number and row number is even, the square is black.
  4. If the sum is odd, the square is white.

Code

#include <iostream>
using namespace std;

bool squareIsWhite(string coordinates) {
    // Convert col letter to number: 'a' -> 1, 'b' -> 2, ..., 'h' -> 8
    int col = coordinates[0] - 'a' + 1;
    // Row number as integer
    int row = coordinates[1] - '0';
    
    // Determine color based on parity of sum of col and row
    return (col + row) % 2 != 0;
}

int main() {
    // Example test cases
    cout << squareIsWhite("a1") << endl; // Output: 0 (False)
    cout << squareIsWhite("h3") << endl; // Output: 0 (False)
    cout << squareIsWhite("c7") << endl; // Output: 1 (True)

    return 0;
}

Time Complexity

The time complexity of this solution is (O(1)) since converting the column letter, converting the row number, and computing the sum parity are all constant-time operations. The space complexity is also (O(1)).

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI