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.

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'The idea is that on a chessboard, the color of a square can be determined by considering the parity (even or odd) of the sum of the column index and row number.
If we treat the columns as numbers (a=1, b=2, ..., h=8), then we find the sum of the column number and row number for each coordinate. If both coordinates have the same parity (both even or both odd), then they have the same color; otherwise, they differ.
This C function calculates the 'color parity' by converting the column letter into an index using 'a' as base, then adds the numeric row. We then check if both coordinates have the same parity.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
Another approach is to precompute the colors in a board pattern represented as a 2D array of binary values (0 for black, 1 for white) and compare values at the given coordinates.
This C function uses a predefined chessboard pattern array to find the color at given coordinates and compare them.
C++
Java
Python
C#
JavaScript
Time Complexity: O(1)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Calculate Parity for Each Coordinate | Time Complexity: O(1) |
| Use Precomputed Board Pattern | Time Complexity: O(1) |
Detect Squares - Leetcode Weekly Contest - Problem 2013 - Python • NeetCode • 40,951 views views
Watch 9 more video solutions →Practice Check if Two Chessboard Squares Have the Same Color with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor