#3274

Check if Two Chessboard Squares Have the Same Color

Easy
MathStringMathematical properties (parity checks)String manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution uses the same logic as the brute force but is more concise. We can directly compute the color based on the coordinates without needing to store intermediate values.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the column index from the character (a-h) as before.
  2. 2Step 2: Calculate the row index from the character (1-8) as before.
  3. 3Step 3: Directly check if the sum of the column and row indices is even or odd for both coordinates.
  4. 4Step 4: Return the comparison result.
solution.py4 lines
1# Full working Python code
2
3def squaresHaveSameColor(coordinate1, coordinate2):
4    return (ord(coordinate1[0]) + int(coordinate1[1])) % 2 == (ord(coordinate2[0]) + int(coordinate2[1])) % 2

Complexity note: The time complexity remains O(1) as we perform a constant number of operations. The space complexity is also O(1) since no additional space is used.

  • 1The chessboard colors alternate, which can be determined by the parity of the sum of the row and column indices.
  • 2The problem can be solved in constant time due to the fixed size of the chessboard.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.