algoadvance

Leetcode 1812. Determine Color of a Chessboard Square

Problem Statement

You are given a coordinate coordinates in the form of a string that represents the position of a square on a standard 8x8 chessboard. The string will consist of two characters:

You need to return a boolean value indicating whether the square is white or not. A white square on a standard chessboard alternates with black squares: starting from the bottom-left corner (a1), which is a black square.

Clarifying Questions

  1. Q: Can input coordinates be invalid, or should we assume it is always valid as per the problem constraints?
    • A: You can assume the input coordinates will always be valid as per the problem constraints.
  2. Q: Should the result be returned as true for white and false for black?
    • A: Yes, true should be returned for a white square and false for a black square.

Strategy

The chessboard’s alternating color pattern can be visualized with this insight:

Here’s how we can implement this strategy:

  1. Convert the column letter to its corresponding numerical index.
  2. Convert the row character to an integer.
  3. Determine the color based on the parity (odd/even) of the sum of the indices.

Code

public class Solution {
    public boolean squareIsWhite(String coordinates) {
        // Convert the column character to a number (a -> 1, b -> 2, ..., h -> 8)
        int column = coordinates.charAt(0) - 'a' + 1;
        // Convert the row character to a number (1 -> 1, 2 -> 2, ..., 8 -> 8)
        int row = coordinates.charAt(1) - '0';

        // Return true if the sum of column + row is odd (white), otherwise false (black)
        return (column + row) % 2 != 0;
    }
}

Time Complexity

The solution has a constant time complexity since the operations performed (character conversion, addition, and modulo) all take constant time:

This solution efficiently determines the color of the chessboard square with minimal computational resources.

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