3274. Check if Two Chessboard Squares Have the Same Color
Problem Description
You are given two strings, coordinate1
and coordinate2
, representing the coordinates of two squares on an 8×8 chessboard.
Each coordinate string consists of:
- A letter (a-h) representing the column
- A number (1-8) representing the row
For example, "a1" represents the bottom-left corner square, and "h8" represents the top-right corner square.
On a standard chessboard, squares alternate between two colors (typically black and white) in a checkered pattern. Your task is to determine if the two given squares have the same color.
Return true
if both squares have the same color, and false
if they have different colors.
The solution works by calculating the difference between the column positions (x-coordinates) and row positions (y-coordinates) of the two squares. If the sum of these differences is even, the squares share the same color. This is because on a chessboard, moving an even number of squares (in any combination of horizontal and vertical moves) will always land you on a square of the same color, while moving an odd number of squares will land you on a square of the opposite color.
The code converts the column letter to a number using ord()
, calculates the differences, and checks if (x + y) % 2 == 0
to determine if the colors match.
Intuition
To understand which squares have the same color on a chessboard, let's first think about the pattern. If we consider the bottom-left square (a1) as black, then moving one square in any direction (up, down, left, or right) changes the color. Moving two squares in the same direction brings us back to the same color.
This creates a pattern: if we assign coordinates to each square where columns are numbered 1-8 and rows are numbered 1-8, we can observe that:
- Square (1,1) is black
- Square (1,2) is white (different color)
- Square (2,1) is white (different color)
- Square (2,2) is black (same as (1,1))
Notice that when both coordinates are odd or both are even, the square is black. When one coordinate is odd and the other is even, the square is white. This means the color depends on whether the sum (column + row)
is even or odd.
Now, to check if two squares have the same color, we don't need to determine the actual color of each square. We just need to check if they follow the same parity pattern.
If square 1 is at (x1, y1)
and square 2 is at (x2, y2)
, they have the same color when:
(x1 + y1)
and(x2 + y2)
have the same parity (both even or both odd)
This is equivalent to checking if (x1 + y1) - (x2 + y2)
is even, which simplifies to checking if (x1 - x2) + (y1 - y2)
is even.
Therefore, we calculate the difference in x-coordinates and y-coordinates between the two squares. If their sum is even, the squares have the same color; if odd, they have different colors.
Learn more about Math patterns.
Solution Approach
The implementation follows directly from our mathematical observation that two squares have the same color if the sum of their coordinate differences is even.
Here's how the solution works step by step:
-
Extract the x-coordinate difference:
- Convert the column letters to numbers using
ord()
function ord(coordinate1[0]) - ord(coordinate2[0])
gives us the difference between column positions- For example, if coordinate1 is "c3" and coordinate2 is "a1", then
ord('c') - ord('a') = 2
- Convert the column letters to numbers using
-
Extract the y-coordinate difference:
- Convert the row characters to integers
int(coordinate1[1]) - int(coordinate2[1])
gives us the difference between row positions- For example, if coordinate1 is "c3" and coordinate2 is "a1", then
3 - 1 = 2
-
Check the parity:
- Add the two differences:
(x + y)
- Check if the sum is even using modulo operator:
(x + y) % 2 == 0
- If the result is
True
, both squares have the same color - If the result is
False
, the squares have different colors
- Add the two differences:
The beauty of this approach is that we don't need to determine the actual color of each square. We only need to check if the total Manhattan distance (sum of absolute differences in each dimension) between the two squares is even or odd. An even distance means same color, odd distance means different colors.
This solution has a time complexity of O(1)
since we're only performing a constant number of operations, and space complexity of O(1)
as we only use two integer variables to store the differences.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through two examples to understand how the solution determines if chess squares have the same color.
Example 1: coordinate1 = "a1", coordinate2 = "c3"
Step 1: Calculate the x-coordinate (column) difference
- Column 'a' →
ord('a')
= 97 - Column 'c' →
ord('c')
= 99 - Difference:
97 - 99 = -2
Step 2: Calculate the y-coordinate (row) difference
- Row '1' →
int('1')
= 1 - Row '3' →
int('3')
= 3 - Difference:
1 - 3 = -2
Step 3: Check if the sum of differences is even
- Sum:
(-2) + (-2) = -4
- Is
-4
even? Yes (-4 % 2 == 0
) - Result:
True
(squares have the same color)
To verify: On a standard chessboard, a1 is a dark square (bottom-left corner), and c3 is also dark. Moving 2 squares right and 2 squares up (total of 4 moves) keeps us on the same color.
Example 2: coordinate1 = "a1", coordinate2 = "h3"
Step 1: Calculate the x-coordinate (column) difference
- Column 'a' →
ord('a')
= 97 - Column 'h' →
ord('h')
= 104 - Difference:
97 - 104 = -7
Step 2: Calculate the y-coordinate (row) difference
- Row '1' →
int('1')
= 1 - Row '3' →
int('3')
= 3 - Difference:
1 - 3 = -2
Step 3: Check if the sum of differences is even
- Sum:
(-7) + (-2) = -9
- Is
-9
even? No (-9 % 2 == 1
) - Result:
False
(squares have different colors)
To verify: a1 is dark, and h3 is light. Moving 7 squares right and 2 squares up (total of 9 moves) lands us on the opposite color.
The key insight: The total number of moves (regardless of direction) determines if we end up on the same color (even moves) or opposite color (odd moves).
Solution Implementation
1class Solution:
2 def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
3 """
4 Check if two chess board coordinates have the same color.
5
6 On a chess board, squares are alternating black and white.
7 Two squares have the same color if the sum of their coordinate differences is even.
8
9 Args:
10 coordinate1: First coordinate in chess notation (e.g., "a1")
11 coordinate2: Second coordinate in chess notation (e.g., "h8")
12
13 Returns:
14 True if both coordinates are on the same color, False otherwise
15 """
16 # Calculate the difference in column positions (a-h mapped to ASCII values)
17 column_diff = ord(coordinate1[0]) - ord(coordinate2[0])
18
19 # Calculate the difference in row positions (1-8)
20 row_diff = int(coordinate1[1]) - int(coordinate2[1])
21
22 # Two squares have the same color if the sum of differences is even
23 # This works because chess board colors alternate in a pattern
24 return (column_diff + row_diff) % 2 == 0
25
1class Solution {
2 /**
3 * Checks if two chess board coordinates are on the same color square.
4 * Chess board squares alternate between black and white.
5 * Two squares have the same color if the sum of their coordinate differences is even.
6 *
7 * @param coordinate1 First chess board coordinate (e.g., "a1")
8 * @param coordinate2 Second chess board coordinate (e.g., "b2")
9 * @return true if both coordinates are on the same color square, false otherwise
10 */
11 public boolean checkTwoChessboards(String coordinate1, String coordinate2) {
12 // Calculate the difference in column positions (letters a-h)
13 int columnDifference = coordinate1.charAt(0) - coordinate2.charAt(0);
14
15 // Calculate the difference in row positions (numbers 1-8)
16 int rowDifference = coordinate1.charAt(1) - coordinate2.charAt(1);
17
18 // Two squares are the same color if the sum of differences is even
19 // This works because chess board colors alternate in a pattern
20 return (columnDifference + rowDifference) % 2 == 0;
21 }
22}
23
1class Solution {
2public:
3 bool checkTwoChessboards(string coordinate1, string coordinate2) {
4 // Calculate the difference in column positions (letters a-h)
5 int columnDifference = coordinate1[0] - coordinate2[0];
6
7 // Calculate the difference in row positions (numbers 1-8)
8 int rowDifference = coordinate1[1] - coordinate2[1];
9
10 // Two squares are the same color if the sum of their differences is even
11 // This works because on a chessboard:
12 // - Moving one square horizontally or vertically changes color
13 // - Moving two squares in any direction keeps the same color
14 // Therefore, if (col1 + row1) and (col2 + row2) have the same parity,
15 // the squares have the same color
16 return (columnDifference + rowDifference) % 2 == 0;
17 }
18};
19
1/**
2 * Checks if two chess board coordinates are on squares of the same color.
3 * On a chess board, squares of the same color have coordinates where the sum of
4 * column (a-h mapped to 1-8) and row (1-8) have the same parity (both even or both odd).
5 *
6 * @param coordinate1 - First chess board coordinate (e.g., "a1", "e5")
7 * @param coordinate2 - Second chess board coordinate (e.g., "h8", "c3")
8 * @returns true if both coordinates are on squares of the same color, false otherwise
9 */
10function checkTwoChessboards(coordinate1: string, coordinate2: string): boolean {
11 // Calculate the difference in column positions (a-h)
12 const columnDifference: number = coordinate1.charCodeAt(0) - coordinate2.charCodeAt(0);
13
14 // Calculate the difference in row positions (1-8)
15 const rowDifference: number = coordinate1.charCodeAt(1) - coordinate2.charCodeAt(1);
16
17 // Two squares are the same color if the sum of their differences is even
18 // This works because moving diagonally (same color) changes both row and column by same parity
19 return (columnDifference + rowDifference) % 2 === 0;
20}
21
Time and Space Complexity
The time complexity is O(1)
because the algorithm performs a fixed number of operations regardless of input size. It calculates the character difference using ord()
, computes the integer difference between positions, and performs a modulo operation - all constant-time operations.
The space complexity is O(1)
because the algorithm only uses two integer variables x
and y
to store intermediate results, requiring constant additional memory regardless of input.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Misunderstanding the Color Pattern Logic
A common mistake is trying to determine the actual color of each square individually before comparing them. Developers might write complex logic like:
# Incorrect approach - overly complicated
def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
color1 = (ord(coordinate1[0]) - ord('a') + int(coordinate1[1])) % 2
color2 = (ord(coordinate2[0]) - ord('a') + int(coordinate2[1])) % 2
return color1 == color2
While this might work, it's unnecessarily complex and prone to off-by-one errors when determining the base color.
Solution: Use the difference-based approach shown in the original solution. You don't need to know the actual colors, just whether the squares differ by an even or odd Manhattan distance.
2. Forgetting to Handle Absolute Values
The current solution works correctly because we're checking parity (even/odd), but conceptually, some might think they need absolute values:
# Unnecessary but not wrong
column_diff = abs(ord(coordinate1[0]) - ord(coordinate2[0]))
row_diff = abs(int(coordinate1[1]) - int(coordinate2[1]))
Since we only care about whether the sum is even or odd, the sign doesn't matter: (-3 + 2) % 2
equals (3 + -2) % 2
.
Solution: The original approach without abs()
is correct and more efficient. The mathematical property (a + b) % 2 = (|a| + |b|) % 2
when considering parity makes absolute values unnecessary.
3. Integer Conversion Oversight
A subtle bug can occur if you forget to convert the row character to an integer:
# Bug: coordinate1[1] is a string character, not an integer row_diff = coordinate1[1] - coordinate2[1] # This will cause a TypeError
Solution: Always remember to convert the row character to integer using int()
before performing arithmetic operations.
4. Incorrect Indexing
Mixing up which index represents column vs row:
# Wrong: coordinate[0] is the column (letter), coordinate[1] is the row (number)
column_diff = int(coordinate1[1]) - int(coordinate2[1]) # This is actually row
row_diff = ord(coordinate1[0]) - ord(coordinate2[0]) # This is actually column
While this specific mistake would still give the correct answer (since we're just summing them), it shows poor understanding of the problem.
Solution: Remember the chess notation format: letter first (column), then number (row). Use meaningful variable names to avoid confusion.
What is the best way of checking if an element exists in a sorted array once in terms of time complexity? Select the best that applies.
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https assets algo monster recursion jpg You first call Ben and ask
Want a Structured Path to Master System Design Too? Don’t Miss This!