3274. Check if Two Chessboard Squares Have the Same Color
Problem Description
You are provided with two strings, coordinate1
and coordinate2
, that represent the coordinates of squares on an 8 x 8
chessboard. The task is to determine if these two squares have the same color. The chessboard squares follow the standard pattern where alternating squares are colored differently, creating a checkered layout. The coordinates are always given with the column letter followed by the row number.
Intuition
To determine if two chessboard squares have the same color, consider how the colors alternate:
- Each square is identified by a letter (column) and a number (row).
- Chessboard columns are represented by letters 'a' to 'h', and rows are numbered from '1' to '8'.
- The pattern alternates such that:
- Squares in columns 'a', 'c', 'e', 'g' are black on odd-numbered rows (1, 3, 5, 7) and white on even-numbered rows (2, 4, 6, 8).
- Squares in columns 'b', 'd', 'f', 'h' are white on odd-numbered rows and black on even-numbered rows.
Using this pattern, the key insight is:
- The combined parity of the column and row, when expressed numerically, determines the color:
- Convert the column to a number using
ord(column) % 2
and the row usingrow % 2
. - Calculate their sum; if the sum is even, the square is one color; if odd, the opposite color.
- Convert the column to a number using
With this understanding, we calculate:
- Convert the column letters to numerical indices and compare the sum of indices and row numbers mod 2 for both coordinates.
- The colors match if the combined checks
(column index + row) % 2
are equal for both coordinates.
Learn more about Math patterns.
Solution Approach
The solution utilizes a straightforward mathematical approach. We leverage the inherent checkered pattern of the chessboard and the properties of even and odd numbers. Here's how the solution is implemented:
-
Coordinate Transformation:
- Convert the column from a letter to a number. This is done by using the ASCII value of the character:
ord(coordinate[0])
. This gives us a numerical representation of the column. - For example,
ord('a')
results in 97. To make 'a' correspond to a base value of 0, calculateord(column) - ord('a')
. This ensures 'a' starts at 0, 'b' at 1, and so forth.
- Convert the column from a letter to a number. This is done by using the ASCII value of the character:
-
Sum Calculation:
- The row from the coordinate is already a simple integer, as it ranges from 1 to 8.
- Calculate the parity of the coordinates by computing
(column_index + row_number) % 2
.
-
Comparison:
- For both coordinates, compute the formula
(ord(coordinate[0]) - ord('a') + int(coordinate[1])) % 2
. - Compare the results for both coordinates. If they are the same, the squares are of the same color.
- For both coordinates, compute the formula
The solution uses this algorithm to determine the parity relationship between the two coordinates:
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
This concise calculation lets us quickly determine if the two squares are the same color, leveraging simple arithmetic and the modular property to handle the checkered pattern efficiently.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's consider two example coordinates on a chessboard: coordinate1 = 'a1'
and coordinate2 = 'c1'
. We will determine if these two squares have the same color using the solution approach explained.
-
Coordinate Transformation:
- For
coordinate1 = 'a1'
:- Column letter 'a' is converted to a number using
ord('a') - ord('a') = 0
. - Row number '1' is already an integer:
int('1') = 1
.
- Column letter 'a' is converted to a number using
- For
coordinate2 = 'c1'
:- Column letter 'c' is converted to a number using
ord('c') - ord('a') = 2
. - Row number '1' is already an integer:
int('1') = 1
.
- Column letter 'c' is converted to a number using
- For
-
Sum Calculation:
- Calculate the parity (even or odd sum) for each coordinate:
- For
coordinate1 = 'a1'
:(0 + 1) % 2 = 1
. - For
coordinate2 = 'c1'
:(2 + 1) % 2 = 1
.
- For
- Calculate the parity (even or odd sum) for each coordinate:
-
Comparison:
- Since the parity for both coordinates is the same (
1
), this indicates that both squares are of the same color.
- Since the parity for both coordinates is the same (
By following these steps, we conclude that the squares at coordinate1 = 'a1'
and coordinate2 = 'c1'
are the same color on the chessboard.
Solution Implementation
1class Solution:
2 def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
3 # Calculate the difference in the column position (represented as letters)
4 column_difference = ord(coordinate1[0]) - ord(coordinate2[0])
5
6 # Calculate the difference in the row position (represented as numbers)
7 row_difference = int(coordinate1[1]) - int(coordinate2[1])
8
9 # Determine if both coordinates are on the same color by checking if the sum of differences is even
10 return (column_difference + row_difference) % 2 == 0
11
1class Solution {
2 /**
3 * Determines if two chessboard coordinates are the same color.
4 *
5 * @param coordinate1 First chessboard coordinate in the format "LetterNumber" (e.g., "A1").
6 * @param coordinate2 Second chessboard coordinate in the format "LetterNumber" (e.g., "B2").
7 * @return True if both coordinates are of the same color, otherwise false.
8 */
9 public boolean checkTwoChessboards(String coordinate1, String coordinate2) {
10 // Calculate the difference in the letter part of the coordinates
11 int xDifference = coordinate1.charAt(0) - coordinate2.charAt(0);
12 // Calculate the difference in the number part of the coordinates
13 int yDifference = coordinate1.charAt(1) - coordinate2.charAt(1);
14 // Both coordinates have the same color if the sum of differences is even
15 return (xDifference + yDifference) % 2 == 0;
16 }
17}
18
1class Solution {
2public:
3 // Function to check if two squares are of the same color on the chessboard
4 bool checkTwoChessboards(string coordinate1, string coordinate2) {
5 // Calculate the difference in the column positions ('a' to 'h')
6 int x_difference = coordinate1[0] - coordinate2[0];
7
8 // Calculate the difference in the row positions ('1' to '8')
9 int y_difference = coordinate1[1] - coordinate2[1];
10
11 // Condition to check if both squares are of the same color
12 // Two squares are of the same color if the sum of differences is even
13 return (x_difference + y_difference) % 2 == 0;
14 }
15};
16
1// This function checks if two chessboard coordinates are on the same color square.
2function checkTwoChessboards(coordinate1: string, coordinate2: string): boolean {
3 // Calculate the difference in the column (x-axis) ASCII values of the two coordinates.
4 const columnDifference = coordinate1.charCodeAt(0) - coordinate2.charCodeAt(0);
5
6 // Calculate the difference in the row (y-axis) ASCII values of the two coordinates.
7 const rowDifference = coordinate1.charCodeAt(1) - coordinate2.charCodeAt(1);
8
9 // Check if the sum of the differences is even.
10 // If even, the two coordinates are on squares of the same color.
11 return (columnDifference + rowDifference) % 2 === 0;
12}
13
Time and Space Complexity
The time complexity of the code is O(1)
. This is because the operations performed (converting characters to their ASCII values, performing arithmetic operations, and evaluating a modulus condition) all take constant time, independent of the input size.
The space complexity of the code is O(1)
. This is due to the fact that the method only uses a fixed amount of extra space for the variables x
and y
, and does not require any additional space that grows with the input size.
Learn more about how to find time and space complexity quickly.
How does merge sort divide the problem into subproblems?
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 algomonster s3 us east 2 amazonaws com recursion jpg You first
Want a Structured Path to Master System Design Too? Don’t Miss This!