LeetCode 3274 - Check if Two Chessboard Squares Have the Same Color
The problem gives us two chessboard coordinates, such as "a1" or "h8", and asks whether the two squares have the same color on a standard 8 x 8 chessboard. A chessboard alternates between black and white squares.
Difficulty: 🟢 Easy
Topics: Math, String
Solution
Problem Understanding
The problem gives us two chessboard coordinates, such as "a1" or "h8", and asks whether the two squares have the same color on a standard 8 x 8 chessboard.
A chessboard alternates between black and white squares. If one square is black, all horizontally or vertically adjacent squares are white, and vice versa. This alternating pattern means the color of a square can be determined entirely from its row and column.
Each coordinate consists of:
- A lowercase letter from
'a'to'h', representing the column - A digit from
'1'to'8', representing the row
For example:
"a1"refers to columna, row1"c3"refers to columnc, row3
The goal is to return:
trueif both squares have the same colorfalseotherwise
The constraints are extremely small:
- Both strings always have length
2 - Coordinates are guaranteed to be valid chessboard positions
This tells us several important things:
- We never need to validate input format
- We never need to worry about invalid letters or numbers
- Performance is not a concern because the input size is constant
A naive implementation could accidentally hardcode board colors incorrectly or mix up whether "a1" starts as black or white. Another possible mistake is forgetting that both the row and column contribute to the color pattern. Fortunately, the board follows a very regular mathematical rule that makes the solution straightforward.
Approaches
Brute Force Approach
A brute-force solution would explicitly model the entire chessboard. We could create an 8 x 8 grid and manually assign colors to every square by alternating between black and white.
For example, we could:
- Build a board representation
- Fill each square with
"black"or"white" - Convert coordinates into indices
- Compare the colors of the two positions
This works because the board pattern is deterministic and finite. Once the board is built correctly, every lookup gives the exact square color.
However, this approach is unnecessarily complicated for such a small task. We do not actually need to construct the board because the color can be computed directly from the coordinate itself.
Optimal Approach
The key observation is that chessboard colors alternate based on the parity of the row and column indices.
If we convert:
- Columns
'a'through'h'into numbers1through8 - Rows
'1'through'8'into integers
then:
- Squares where
(row + column)is even have one color - Squares where
(row + column)is odd have the other color
For example:
"a1"→1 + 1 = 2→ even"c3"→3 + 3 = 6→ even
Since both sums have the same parity, the squares have the same color.
This eliminates the need for any board construction and allows the answer to be computed in constant time.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| Brute Force | O(1) | O(1) | Builds or simulates the entire chessboard |
| Optimal | O(1) | O(1) | Uses parity of row + column to determine color |
Algorithm Walkthrough
- Read the column character from each coordinate.
The first character represents the column. For example, 'a' corresponds to the first column and 'h' corresponds to the eighth column.
2. Convert the column letter into a numeric value.
We can use ASCII arithmetic:
'a'becomes1'b'becomes2- ...
'h'becomes8
This is done by subtracting 'a' and adding 1.
3. Read the row digit from each coordinate.
The second character is the row number from '1' to '8'.
4. Convert the row character into an integer.
For example:
'1'becomes1'8'becomes8
- Compute the parity of each square.
Add the row and column values together.
If the sum is:
- Even, the square has one color
- Odd, the square has the opposite color
- Compare the parities of the two squares.
If both sums are either even or odd, then the squares have the same color. Otherwise, they have different colors.
Why it works
Chessboard coloring alternates every time we move one square horizontally or vertically. This means the parity of (row + column) completely determines the color.
Two squares share the same color if and only if their parities match:
- even/even
- odd/odd
If the parities differ, the colors differ as well.
Python Solution
class Solution:
def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
def get_parity(coordinate: str) -> int:
column = ord(coordinate[0]) - ord('a') + 1
row = int(coordinate[1])
return (column + row) % 2
return get_parity(coordinate1) == get_parity(coordinate2)
The solution defines a helper function called get_parity that computes whether a square belongs to the even or odd color group.
The column letter is converted into a numeric index using ASCII arithmetic. The row digit is converted into an integer using int().
The expression:
(column + row) % 2
computes the parity of the square. Two coordinates have the same color exactly when their parities match.
The final return statement compares the two parities directly.
Go Solution
func checkTwoChessboards(coordinate1 string, coordinate2 string) bool {
getParity := func(coordinate string) int {
column := int(coordinate[0]-'a') + 1
row := int(coordinate[1] - '0')
return (column + row) % 2
}
return getParity(coordinate1) == getParity(coordinate2)
}
The Go implementation follows the same logic as the Python version. Since Go strings are byte slices, characters are accessed using indexing like coordinate[0].
The row digit is converted into an integer by subtracting '0', which is the standard Go approach for digit conversion.
No special handling for overflow or invalid input is required because the constraints guarantee valid chessboard coordinates and the numbers involved are extremely small.
Worked Examples
Example 1
Input:
coordinate1 = "a1"
coordinate2 = "c3"
Step-by-step evaluation:
| Coordinate | Column | Column Value | Row | Sum | Parity |
|---|---|---|---|---|---|
| a1 | a | 1 | 1 | 2 | 0 |
| c3 | c | 3 | 3 | 6 | 0 |
Both parities are 0, so both squares have the same color.
Output:
true
Example 2
Input:
coordinate1 = "a1"
coordinate2 = "h3"
Step-by-step evaluation:
| Coordinate | Column | Column Value | Row | Sum | Parity |
|---|---|---|---|---|---|
| a1 | a | 1 | 1 | 2 | 0 |
| h3 | h | 8 | 3 | 11 | 1 |
The parities differ, so the squares have different colors.
Output:
false
Complexity Analysis
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(1) | Only a few arithmetic operations are performed |
| Space | O(1) | No extra data structures are used |
The algorithm performs a constant number of operations regardless of the input because the coordinate length is fixed at two characters. No loops, recursion, or auxiliary storage proportional to input size are required.
Test Cases
solution = Solution()
# Provided examples
assert solution.checkTwoChessboards("a1", "c3") == True # same color
assert solution.checkTwoChessboards("a1", "h3") == False # different colors
# Same square
assert solution.checkTwoChessboards("d4", "d4") == True # identical coordinates
# Opposite corners
assert solution.checkTwoChessboards("a1", "h8") == True # same color
# Adjacent horizontally
assert solution.checkTwoChessboards("a1", "b1") == False # adjacent squares differ
# Adjacent vertically
assert solution.checkTwoChessboards("c3", "c4") == False # adjacent squares differ
# Random same-color pair
assert solution.checkTwoChessboards("b2", "f6") == True # both even parity
# Random different-color pair
assert solution.checkTwoChessboards("g5", "h5") == False # neighboring columns
# Edge coordinates
assert solution.checkTwoChessboards("a8", "h1") == False # different parity
# Another same-color pair
assert solution.checkTwoChessboards("e2", "g4") == True # same parity
| Test | Why |
|---|---|
"a1" vs "c3" |
Verifies the primary example |
"a1" vs "h3" |
Verifies different colors |
"d4" vs "d4" |
Checks identical coordinates |
"a1" vs "h8" |
Tests opposite board corners |
"a1" vs "b1" |
Tests horizontal adjacency |
"c3" vs "c4" |
Tests vertical adjacency |
"b2" vs "f6" |
Confirms even parity matching |
"g5" vs "h5" |
Confirms neighboring columns differ |
"a8" vs "h1" |
Tests edge positions |
"e2" vs "g4" |
Additional same-color validation |
Edge Cases
One important edge case is when both coordinates are identical, such as "d4" and "d4". A buggy implementation might accidentally compare references or mishandle repeated input values. Since both coordinates clearly represent the same square, the parity values are identical, and the implementation correctly returns True.
Another important case involves adjacent squares, such as "a1" and "b1". Adjacent chessboard squares always have opposite colors. A naive implementation that only checks rows or only checks columns would fail here. The parity-based solution handles this naturally because moving one square changes the parity.
A third important edge case involves coordinates on opposite ends of the board, such as "a1" and "h8". Even though these squares are far apart, they still share the same color because both coordinates produce even parity sums. This verifies that the algorithm depends only on parity, not physical distance on the board.