LeetCode 1812: Determine Color of a Chessboard Square

MathString

Problem Description

Explanation

To determine the color of a chessboard square, we can observe that the color of a square is determined by the sum of its row index and column index. If the sum is even, the square is white, and if the sum is odd, the square is black. We can use this observation to solve the problem by converting the given coordinates to numeric indices and then checking if the sum of the indices is even or odd.

  • Convert the letter coordinate to a numeric index (0 to 7) representing the column.
  • Convert the number coordinate to a numeric index (0 to 7) representing the row.
  • Check if the sum of the row and column indices is even or odd to determine the color of the square.

Time Complexity

The time complexity of this algorithm is O(1) as it involves simple arithmetic operations to determine the color of the square.

Space Complexity

The space complexity of this algorithm is O(1) as we are not using any extra space that grows with the input size.

Solutions

class Solution {
    public boolean squareIsWhite(String coordinates) {
        int col = coordinates.charAt(0) - 'a';
        int row = coordinates.charAt(1) - '1';
        return (col + row) % 2 == 0;
    }
}

Loading editor...