#1812

Determine Color of a Chessboard Square

Easy
MathStringMathString 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 leverages the same logic as the brute force but simplifies the process by directly calculating the color based on the sum of the indices. This approach is efficient and straightforward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the letter part of the coordinate to a number (1 for 'a', 2 for 'b', ..., 8 for 'h').
  2. 2Step 2: Convert the number part of the coordinate to an integer.
  3. 3Step 3: Return true if the sum of the column and row is odd (indicating a white square), false otherwise.
solution.py2 lines
1def squareIsWhite(coordinates):
2    return (ord(coordinates[0]) - ord('a') + 1 + int(coordinates[1])) % 2 == 1

Complexity note: Both time and space complexity remain O(1) as we are still performing a constant number of operations and using a fixed amount of space.

  • 1The chessboard alternates colors, so the sum of the column and row determines the color.
  • 2Odd sums correspond to white squares, while even sums correspond to black squares.

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