LeetCode 1812 - Determine Color of a Chessboard Square

This problem asks us to determine whether a given chessboard square is white or black based on its coordinate. The input is a string of length two, where the first character is a lowercase letter from 'a' to 'h', representing the column, and the second character is a digit…

LeetCode Problem 1812

Difficulty: 🟢 Easy
Topics: Math, String

Solution

LeetCode 1812 - Determine Color of a Chessboard Square

Problem Understanding

This problem asks us to determine whether a given chessboard square is white or black based on its coordinate. The input is a string of length two, where the first character is a lowercase letter from 'a' to 'h', representing the column, and the second character is a digit from '1' to '8', representing the row.

A standard chessboard alternates colors between adjacent squares. If one square is black, then every horizontally or vertically adjacent square is white. According to the problem statement, the square "a1" is black, and the coloring alternates from there.

The task is to return:

  • true if the given square is white
  • false if the given square is black

For example:

  • "a1" is black
  • "h3" is white
  • "c7" is black

The constraints are very small. The input always contains exactly two characters, and the coordinate is guaranteed to be valid. This means we do not need to worry about malformed input, invalid letters, or invalid numbers.

The important observation is that chessboard colors follow a repeating parity pattern. Squares alternate colors based on the sum of their row and column positions.

Some edge cases that could cause confusion include:

  • The starting square "a1" being black instead of white
  • Correctly converting letters into numerical positions
  • Ensuring parity logic is applied consistently across all rows and columns

Because the input is guaranteed valid, we do not need additional validation logic.

Approaches

Brute Force Approach

A brute-force solution would explicitly model the entire chessboard. We could create an 8×8 grid and manually assign colors to every square by alternating black and white.

For example, we could:

  1. Create a two-dimensional array
  2. Fill it with alternating boolean values
  3. Convert the coordinate into row and column indices
  4. Return the stored value

This approach works because a chessboard has a fixed and known structure. Once the board is constructed correctly, every coordinate lookup gives the correct answer.

However, this approach is unnecessarily complicated for such a small problem. Constructing a full board uses extra memory and adds implementation complexity when the color can be computed directly with a mathematical observation.

Optimal Approach

The key insight is that chessboard colors depend entirely on parity.

If we convert:

  • 'a' to 1
  • 'b' to 2
  • and so on

then:

  • squares with an even sum of (column + row) are black
  • squares with an odd sum are white

For example:

Coordinate Column Value Row Value Sum Color
a1 1 1 2 Black
a2 1 2 3 White
b1 2 1 3 White
b2 2 2 4 Black

This allows us to compute the answer directly in constant time.

Approach Comparison

Approach Time Complexity Space Complexity Notes
Brute Force O(1) O(1) Builds and stores the entire chessboard
Optimal O(1) O(1) Uses parity of row and column values

Algorithm Walkthrough

  1. Extract the column letter and row digit from the input string.
  2. Convert the column letter into a numerical position. Since characters are stored using ASCII values, we can compute:
  • 'a' → 1
  • 'b' → 2
  • ...
  • 'h' → 8

This is done by subtracting 'a' from the character and adding 1. 3. Convert the row character into an integer digit. 4. Add the column value and row value together. 5. Determine whether the sum is odd or even.

  • Odd sum → white square
  • Even sum → black square
  1. Return true if the sum is odd, otherwise return false.

Why it works

Chessboard coloring alternates on every move horizontally or vertically. Starting from "a1" as black, every neighboring square changes color. This creates a parity pattern where all squares with the same parity share the same color.

Because "a1" has coordinates (1,1) and sum 2, all even sums are black. Therefore, all odd sums must be white. The algorithm directly checks this invariant.

Python Solution

class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        column = ord(coordinates[0]) - ord('a') + 1
        row = int(coordinates[1])

        return (column + row) % 2 == 1

The implementation first converts the column letter into a numerical index using the ord() function. The expression:

ord(coordinates[0]) - ord('a') + 1

maps 'a' to 1, 'b' to 2, and so on.

Next, the row character is converted into an integer using int().

The algorithm then adds the two values together and checks whether the sum is odd. If the sum is odd, the square is white, so the method returns True. Otherwise, it returns False.

The implementation is compact because the mathematical relationship completely determines the answer.

Go Solution

func squareIsWhite(coordinates string) bool {
    column := int(coordinates[0]-'a') + 1
    row := int(coordinates[1] - '0')

    return (column+row)%2 == 1
}

The Go implementation follows the same logic as the Python version. Characters are treated as byte values, so subtracting 'a' converts the column into a zero-based index. Adding 1 converts it into the desired range from 1 to 8.

The row digit is converted into an integer by subtracting '0'.

There are no concerns about integer overflow because all values are very small. Since the input length is guaranteed to be exactly two characters, no additional bounds checks are necessary.

Worked Examples

Example 1

Input:

coordinates = "a1"

Step-by-step evaluation:

Step Value
Column character 'a'
Column value 1
Row character '1'
Row value 1
Sum 2
Sum parity Even
Result False

The square is black.

Example 2

Input:

coordinates = "h3"

Step-by-step evaluation:

Step Value
Column character 'h'
Column value 8
Row character '3'
Row value 3
Sum 11
Sum parity Odd
Result True

The square is white.

Example 3

Input:

coordinates = "c7"

Step-by-step evaluation:

Step Value
Column character 'c'
Column value 3
Row character '7'
Row value 7
Sum 10
Sum parity Even
Result False

The square is black.

Complexity Analysis

Measure Complexity Explanation
Time O(1) Only a few arithmetic operations are performed
Space O(1) No extra data structures are used

The algorithm performs a constant number of operations regardless of the input. Since the chessboard size is fixed and the input length is always two characters, the runtime and memory usage never grow.

Test Cases

solution = Solution()

assert solution.squareIsWhite("a1") == False  # Bottom-left corner, black
assert solution.squareIsWhite("h3") == True   # Example white square
assert solution.squareIsWhite("c7") == False  # Example black square

assert solution.squareIsWhite("a2") == True   # Adjacent vertical square
assert solution.squareIsWhite("b1") == True   # Adjacent horizontal square
assert solution.squareIsWhite("b2") == False  # Same parity as a1

assert solution.squareIsWhite("h8") == False  # Opposite corner, black
assert solution.squareIsWhite("g7") == False  # Another even parity square
assert solution.squareIsWhite("d5") == True   # Odd parity square

assert solution.squareIsWhite("e4") == True   # Middle board white square
assert solution.squareIsWhite("f6") == False  # Middle board black square
Test Why
"a1" Verifies starting black square
"h3" Confirms white square detection
"c7" Confirms black square detection
"a2" Tests vertical alternation
"b1" Tests horizontal alternation
"b2" Verifies parity consistency
"h8" Tests opposite corner
"g7" Tests another even parity square
"d5" Tests odd parity in middle board
"e4" Additional white square validation
"f6" Additional black square validation

Edge Cases

One important edge case is the starting square "a1". Many people intuitively assume the bottom-left square of a chessboard is white, but in this problem it is explicitly black. If the parity rule is reversed accidentally, every result becomes incorrect. The implementation handles this correctly because it treats even sums as black.

Another important case involves the transition between columns. For example, "a2" and "b1" are both white even though they differ in both row and column. A naive implementation that only checks one coordinate could fail here. The solution correctly combines both coordinates and checks their parity together.

A third important edge case is handling the maximum coordinate "h8". This square lies at the opposite corner of the board and has sum 16, which is even. The implementation correctly identifies it as black. This confirms that the parity logic works consistently across the entire board.