# Check if Two Chessboard Squares Have the Same Color
**Difficulty:** EASY
[External](https://leetcode.com/problems/check-if-two-chessboard-squares-have-the-same-color)
Canonical: https://scaleengineer.com/dsa/problems/check-if-two-chessboard-squares-have-the-same-color
**Patterns:** [Math](https://scaleengineer.com/dsa/patterns/math)
**Data structures:** String
---
## Problem
You are given two strings, `coordinate1` and `coordinate2`, representing the coordinates of a square on an `8 x 8` chessboard.

Below is the chessboard for reference.

![](https://assets.glich.co/dsa/check-if-two-chessboard-squares-have-the-same-color/image0.png)

Return `true` if these two squares have the same color and `false` otherwise.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first (indicating its column), and the number second (indicating its row).

**Example 1:**

**Input:** coordinate1 = "a1", coordinate2 = "c3"

**Output:** true

**Explanation:**

Both squares are black.

**Example 2:**

**Input:** coordinate1 = "a1", coordinate2 = "h3"

**Output:** false

**Explanation:**

Square `"a1"` is black and `"h3"` is white.

**Constraints:**

* `coordinate1.length == coordinate2.length == 2`
* `'a' <= coordinate1[0], coordinate2[0] <= 'h'`
* `'1' <= coordinate1[1], coordinate2[1] <= '8'`

# Approaches
## Individual Color Calculation
This approach involves determining the color of each square individually and then comparing them. We can create a helper function that takes a coordinate string and returns its color, represented numerically (e.g., 0 for black, 1 for white). The main function then calls this helper for both coordinates and checks if the results are identical.
**Time:** O(1) - The time taken does not depend on the input size. It involves a fixed number of character operations, arithmetic calculations, and comparisons. · **Space:** O(1) - Constant extra space is used, as we only need a few variables to store the coordinates and colors.
**Pros:** The logic is very clear and easy to understand.; It promotes code reuse by separating the color calculation logic into a helper function.
**Cons:** Slightly less performant as it involves more operations (two separate color calculations) than the most optimal approach.; Can be considered verbose for such a simple problem.
### Explanation
The color of a square on a chessboard follows a consistent pattern based on its position. If we represent the columns 'a' through 'h' as numbers 0 through 7 and rows '1' through '8' as 0 through 7, a square at `(row, col)` is one color if `row + col` is even, and the other color if `row + col` is odd. This approach formalizes this logic into a reusable function.

We define a helper method that encapsulates the logic for finding a single square's color. This method parses the coordinate, calculates the sum of its numeric indices, and returns the parity of the sum. The main method then uses this helper to find the color of each of the two given squares and compares them.

```java
class Solution {
    /**
     * Determines the color of a square, represented as 0 or 1.
     * @param coordinate The algebraic notation of the square (e.g., "a1").
     * @return 0 if the sum of 0-indexed coordinates is even, 1 otherwise.
     */
    private int getColor(String coordinate) {
        int col = coordinate.charAt(0) - 'a';
        int row = coordinate.charAt(1) - '1';
        return (col + row) % 2;
    }

    public boolean squareIsSameColor(String coordinate1, String coordinate2) {
        // Get the color of each square and compare them.
        return getColor(coordinate1) == getColor(coordinate2);
    }
}
```
While this approach is perfectly valid and easy to read, it performs the calculation in two distinct steps. A more streamlined approach could combine these steps.
### Algorithm
- Create a helper function, for instance `getColor(coordinate)`, that returns an integer representing the color of a square (e.g., 0 for black, 1 for white).
- Inside the helper function, parse the input `coordinate` string into 0-indexed column and row integers. For a coordinate like `"c3"`, the column index would be `c` - `a` = 2, and the row index would be `3` - `1` = 2.
- Calculate the sum of the column and row indices.
- The color is determined by the parity of this sum. Return `(col + row) % 2`.
- In the main function, call this `getColor` helper for both `coordinate1` and `coordinate2`.
- Compare the two returned color values. If they are equal, the squares have the same color, so return `true`. Otherwise, return `false`.

## Direct Parity Comparison
This highly efficient approach leverages a mathematical property of the chessboard's coloring pattern and character encoding. It recognizes that the color of a square depends on the parity of the sum of its coordinates. By comparing the parities directly in a single expression, we can solve the problem with minimal computation.
**Time:** O(1) - The solution involves a handful of fixed-time operations, making it constant time. · **Space:** O(1) - No extra space is used beyond a few variables for the calculation.
**Pros:** Extremely efficient, requiring the minimum number of operations.; Very concise and elegant one-line solution.
**Cons:** The direct use of character ASCII values for the parity check might seem non-obvious or magical to someone unfamiliar with the underlying property.
### Explanation
Two squares `(col1, row1)` and `(col2, row2)` have the same color if the parity of `col1 + row1` is the same as the parity of `col2 + row2`. This can be written as `(col1 + row1) % 2 == (col2 + row2) % 2`.

Interestingly, we don't need to convert the characters to 0-indexed integers fully. Let's analyze the parity calculation:
- The numeric column index is `c - 'a'`. The numeric row index is `r - '1'`.
- The sum is `(c - 'a') + (r - '1')`, which equals `c + r - ('a' + '1')`.
- The ASCII value of 'a' is 97 and '1' is 49. Their sum is 146, which is an even number.
- The parity of `X - Y` is the same as the parity of `X` if `Y` is even. Therefore, `(c + r - 146) % 2` is the same as `(c + r) % 2`.

This means we can just sum the ASCII values of the characters in each coordinate and compare the parities of these sums. This leads to an extremely concise and fast solution.

```java
class Solution {
    public boolean squareIsSameColor(String coordinate1, String coordinate2) {
        // The color of a square is determined by the parity of the sum of its coordinates.
        // For a square "a1", col='a', row='1'.
        // The numeric indices are (col - 'a') and (row - '1').
        // The sum is (col - 'a') + (row - '1') = col + row - ('a' + '1').
        // Since 'a' + '1' is even, the parity of the sum of indices is the same as the
        // parity of the sum of the character's ASCII values (col + row).
        // So, we check if (c1 + r1) and (c2 + r2) have the same parity.
        
        int sum1 = coordinate1.charAt(0) + coordinate1.charAt(1);
        int sum2 = coordinate2.charAt(0) + coordinate2.charAt(1);
        
        return sum1 % 2 == sum2 % 2;
    }
}
```
### Algorithm
- Extract the column and row characters from the first coordinate: `c1` and `r1`.
- Extract the column and row characters from the second coordinate: `c2` and `r2`.
- The key insight is that two squares have the same color if and only if the sum of their coordinate indices have the same parity.
- The parity of `(char_col - 'a') + (char_row - '1')` is identical to the parity of `char_col + char_row` because `'a' + '1'` is an even number, and subtracting an even number does not change the parity of a value.
- Therefore, we can directly compare the parity of the sum of the ASCII values of the characters for each coordinate.
- The final check is `(c1 + r1) % 2 == (c2 + r2) % 2`.

# Solutions
### Java

```java
class Solution {
public
  boolean checkTwoChessboards(String coordinate1, String coordinate2) {
    int x = coordinate1.charAt(0) - coordinate2.charAt(0);
    int y = coordinate1.charAt(1) - coordinate2.charAt(1);
    return (x + y) % 2 == 0;
  }
}

```

### CPP

```cpp
class Solution {
public:
  bool checkTwoChessboards(string coordinate1, string coordinate2) {
    int x = coordinate1[0] - coordinate2[0];
    int y = coordinate1[1] - coordinate2[1];
    return (x + y) % 2 == 0;
  }
};

```

### Python

```python
class Solution : def checkTwoChessboards ( self , coordinate1 : str , coordinate2 : str ) -> bool : x = ord ( coordinate1 [ 0 ]) - ord ( coordinate2 [ 0 ]) y = int ( coordinate1 [ 1 ]) - int ( coordinate2 [ 1 ]) return ( x + y ) % 2 == 0
```
