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.
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).
Examples
Example 1
|
|
Example 2
|
|
Constraints
coordinate1.length == coordinate2.length == 2
'a' <= coordinate1[0], coordinate2[0] <= 'h'
'1' <= coordinate1[1], coordinate2[1] <= '8'
Solution
Method 1 – Parity Calculation
Intuition
On a chessboard, the color of a square is determined by the parity of the sum of its row and column indices. If two squares have the same parity, they have the same color.
Reasoning
Columns are labeled ‘a’ to ‘h’ (1 to 8) and rows ‘1’ to ‘8’. For a square, if (column index + row index) is even, it’s black; if odd, it’s white. Thus, two squares have the same color if their parities match.
Approach
- Convert the column letter to a number (a=1, b=2, …, h=8).
- Convert the row character to a number (1-8).
- For both coordinates, compute the sum of column and row indices and check their parity.
- Return true if both parities match, otherwise false.
Edge cases:
- Both coordinates are the same.
Code
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(1)
, as all operations are constant time. - 🧺 Space complexity:
O(1)
, as only a few variables are used.