Facebook Pixel

1812. Determine Color of a Chessboard Square

Problem Description

You are given a string coordinates that represents the position of a square on a standard chessboard. The string consists of a letter (a-h) followed by a number (1-8), where the letter indicates the column and the number indicates the row.

A standard chessboard has an 8×8 grid with alternating black and white squares. The square at position 'a1' (bottom-left corner) is black, and the colors alternate from there.

Your task is to determine the color of the square at the given coordinates. Return true if the square is white, and false if the square is black.

The input will always be a valid chessboard coordinate with the letter first and the number second.

For example:

  • 'a1' is a black square (return false)
  • 'h3' is a white square (return true)
  • 'c7' is a white square (return true)

The solution uses the pattern that the sum of a square's coordinates determines its color. Converting both the letter and number to their numeric values and checking if their sum is odd (white) or even (black) provides the answer.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

Let's think about how the chessboard pattern works. If we look at the board, we notice that colors alternate in a very specific way - moving one square in any direction (horizontally or vertically) changes the color.

If we assign numeric values to both the column letters (a=1, b=2, c=3, etc.) and use the row numbers as they are, we can observe an interesting pattern. For square 'a1', we have column value 1 and row value 1, giving us a sum of 2. For 'a2', we get 1 + 2 = 3. For 'b1', we get 2 + 1 = 3. For 'b2', we get 2 + 2 = 4.

Notice how adjacent squares always have sums that differ by 1? This is because moving to an adjacent square changes exactly one coordinate by 1, which changes the sum by 1.

Since adjacent squares have opposite colors and their coordinate sums differ by 1 (one is odd, one is even), we can deduce that all squares with an even sum have the same color, and all squares with an odd sum have the opposite color.

Looking at 'a1' which is black and has a sum of 2 (even), we can determine that all squares with even sums are black, and all squares with odd sums are white.

In the code, ord(coordinates[0]) gives us the ASCII value of the letter (which maintains the relative differences between columns), and ord(coordinates[1]) gives us the ASCII value of the digit. While these aren't the exact values 1-8, the parity (odd/even nature) of their sum still correctly determines the color since ASCII values for consecutive characters differ by 1.

Learn more about Math patterns.

Solution Approach

Based on our pattern recognition, we implement the solution by checking if the sum of the coordinate values is odd or even.

The implementation follows these steps:

  1. Extract coordinate values: We take the input string coordinates and access its two characters:

    • coordinates[0] gives us the letter (column)
    • coordinates[1] gives us the number (row)
  2. Convert to numeric values: We use the ord() function to get ASCII values:

    • ord(coordinates[0]) converts the letter to its ASCII value (e.g., 'a' becomes 97, 'b' becomes 98, etc.)
    • ord(coordinates[1]) converts the digit character to its ASCII value (e.g., '1' becomes 49, '2' becomes 50, etc.)
  3. Calculate the sum: We add these two ASCII values together:

    • ord(coordinates[0]) + ord(coordinates[1])
  4. Check parity: We use the modulo operator to determine if the sum is odd or even:

    • (ord(coordinates[0]) + ord(coordinates[1])) % 2
    • If the result equals 1, the sum is odd, meaning the square is white
    • If the result equals 0, the sum is even, meaning the square is black
  5. Return the result: The expression % 2 == 1 directly returns True for white squares and False for black squares.

The beauty of this solution is that we don't need to convert the coordinates to exact board positions (1-8). Since consecutive ASCII values differ by 1, the parity relationship is preserved. For example, 'a' + '1' gives 97 + 49 = 146 (even), while 'a' + '2' gives 97 + 50 = 147 (odd), maintaining the alternating pattern of the chessboard.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with the coordinate 'c7':

  1. Extract the characters:

    • Column character: 'c'
    • Row character: '7'
  2. Convert to ASCII values:

    • ord('c') = 99
    • ord('7') = 55
  3. Calculate the sum:

    • 99 + 55 = 154
  4. Check if the sum is odd or even:

    • 154 % 2 = 0 (even)
  5. Determine the color:

    • Since the sum is even (remainder is 0), the expression 154 % 2 == 1 evaluates to False
    • However, let's verify our logic...

Actually, let me recalculate with a clearer approach. Looking at the pattern described:

  • 'a1' is black (column 1, row 1, sum = 2, even → black)
  • Adjacent squares alternate colors

For 'c7':

  • If we map 'c' to 3 and keep row as 7: 3 + 7 = 10 (even → black)
  • Using ASCII: 99 + 55 = 154 (even)

Since the parity is preserved, 'c7' should be black according to our rule.

But wait - let's verify with 'h3' which the problem states is white:

  • 'h' is the 8th column, row 3: 8 + 3 = 11 (odd → white) ✓
  • Using ASCII: ord('h') = 104, ord('3') = 51: 104 + 51 = 155 (odd → white) ✓

So our solution correctly identifies:

  • Even sum → Black square → return False
  • Odd sum → White square → return True

The final result for 'c7': (99 + 55) % 2 == 1154 % 2 == 10 == 1False (black square)

Solution Implementation

1class Solution:
2    def squareIsWhite(self, coordinates: str) -> bool:
3        """
4        Determine if a chess board square is white based on its coordinates.
5      
6        Chess board pattern:
7        - Bottom-left square (a1) is black
8        - Colors alternate in a checkerboard pattern
9        - When column letter (a-h) and row number (1-8) have the same parity, square is black
10        - When column letter and row number have different parity, square is white
11      
12        Args:
13            coordinates: A string of length 2 representing chess board position (e.g., "a1", "h3")
14                        First character is column (a-h), second is row (1-8)
15      
16        Returns:
17            True if the square is white, False if black
18        """
19        # Get ASCII value of column letter (a-h)
20        column_value = ord(coordinates[0])
21      
22        # Get ASCII value of row number (1-8)
23        row_value = ord(coordinates[1])
24      
25        # Sum of ASCII values determines color:
26        # - If sum is odd, the square is white
27        # - If sum is even, the square is black
28        # This works because 'a' has odd ASCII (97) and '1' has odd ASCII (49)
29        # So a1 has even sum (black), a2 has odd sum (white), etc.
30        total_sum = column_value + row_value
31      
32        return total_sum % 2 == 1
33
1class Solution {
2    /**
3     * Determines if a square on a chessboard is white.
4     * 
5     * On a standard chessboard:
6     * - Squares are identified by a letter (a-h) and a number (1-8)
7     * - The square a1 is black, and colors alternate in a checkerboard pattern
8     * - A square is white if the sum of its coordinates has odd parity
9     * 
10     * @param coordinates A string of length 2 representing the square (e.g., "a1", "h3")
11     * @return true if the square is white, false if it's black
12     */
13    public boolean squareIsWhite(String coordinates) {
14        // Extract the column letter and row number from the coordinates
15        char columnLetter = coordinates.charAt(0);  // 'a' to 'h'
16        char rowNumber = coordinates.charAt(1);      // '1' to '8'
17      
18        // Calculate the sum of ASCII values of both characters
19        // For a white square, this sum will be odd
20        // For a black square, this sum will be even
21        int coordinateSum = columnLetter + rowNumber;
22      
23        // Check if the sum is odd (remainder 1 when divided by 2)
24        boolean isWhite = (coordinateSum % 2 == 1);
25      
26        return isWhite;
27    }
28}
29
1class Solution {
2public:
3    /**
4     * Determines if a chess square is white based on its coordinates.
5     * 
6     * @param coordinates A string of length 2 representing a chess square.
7     *                    First character is a column letter ('a'-'h').
8     *                    Second character is a row number ('1'-'8').
9     * @return true if the square is white, false if it's black.
10     * 
11     * Logic: On a chessboard, squares alternate in color.
12     * - If (column + row) is odd, the square is white.
13     * - If (column + row) is even, the square is black.
14     * This works because ASCII values preserve the alternating pattern.
15     */
16    bool squareIsWhite(string coordinates) {
17        // Extract column letter and row digit
18        char columnLetter = coordinates[0];  // 'a' to 'h'
19        char rowDigit = coordinates[1];       // '1' to '8'
20      
21        // Calculate sum of ASCII values
22        int asciiSum = columnLetter + rowDigit;
23      
24        // Check if sum is odd (white square) or even (black square)
25        bool isWhite = (asciiSum % 2) == 1;
26      
27        return isWhite;
28    }
29};
30
1/**
2 * Determines if a chess board square is white based on its coordinates.
3 * Chess board squares alternate between white and black.
4 * A square is white if the sum of its column (a-h) and row (1-8) values is odd.
5 * 
6 * @param coordinates - A string representing the chess square (e.g., "a1", "h8")
7 * @returns true if the square is white, false if it's black
8 */
9function squareIsWhite(coordinates: string): boolean {
10    // Get ASCII value of the column letter (a-h)
11    const columnValue: number = coordinates.charCodeAt(0);
12  
13    // Get ASCII value of the row number (1-8)
14    const rowValue: number = coordinates.charCodeAt(1);
15  
16    // Sum the ASCII values
17    const sum: number = columnValue + rowValue;
18  
19    // Check if sum is odd using bitwise AND with 1
20    // If the least significant bit is 1, the number is odd (white square)
21    const isOdd: boolean = (sum & 1) === 1;
22  
23    return isOdd;
24}
25

Time and Space Complexity

The time complexity is O(1) because the algorithm performs a fixed number of operations regardless of input:

  • Two ord() function calls to get ASCII values of characters
  • One addition operation
  • One modulo operation
  • One comparison operation

All these operations take constant time.

The space complexity is O(1) because the algorithm uses only a constant amount of extra space:

  • No additional data structures are created
  • Only stores the intermediate result of the arithmetic operations
  • The space used does not scale with input size

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Incorrect Coordinate-to-Number Conversion

A common mistake is trying to convert the coordinates to their actual board positions (1-8 for both row and column) before checking parity. This leads to unnecessary complexity and potential errors.

Incorrect approach:

def squareIsWhite(self, coordinates: str) -> bool:
    # Trying to convert to actual board positions
    column = ord(coordinates[0]) - ord('a') + 1  # Convert a-h to 1-8
    row = int(coordinates[1])  # Convert '1'-'8' to 1-8
    return (column + row) % 2 == 0  # WRONG! This inverts the answer

Why it fails: When you convert 'a' to 1 and '1' to 1, their sum becomes 2 (even), but a1 is actually black. The parity relationship gets inverted.

Solution: Use ASCII values directly without conversion. The ASCII values preserve the correct parity relationship.

2. Confusing Which Parity Means Which Color

Another pitfall is getting confused about whether odd or even sums correspond to white or black squares.

Incorrect approach:

def squareIsWhite(self, coordinates: str) -> bool:
    return (ord(coordinates[0]) + ord(coordinates[1])) % 2 == 0  # Returns True for even (black)

Why it fails: This returns True when the square is black, not white.

Solution: Remember that with ASCII values:

  • 'a1' → 97 + 49 = 146 (even) → black square
  • 'a2' → 97 + 50 = 147 (odd) → white square
  • Therefore: odd sum = white, even sum = black

3. Over-complicating with Explicit Mappings

Some might create unnecessary mappings or use complex conditional logic.

Overcomplicated approach:

def squareIsWhite(self, coordinates: str) -> bool:
    column_map = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8}
    column = column_map[coordinates[0]]
    row = int(coordinates[1])
  
    if column % 2 == 1:  # odd column
        return row % 2 == 0  # even row for white
    else:  # even column
        return row % 2 == 1  # odd row for white

Why it's problematic: While this might work, it's unnecessarily verbose and harder to maintain. It also increases the chance of logical errors.

Solution: Stick to the simple ASCII sum approach - it's elegant, concise, and less error-prone.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

What are the most two important steps in writing a depth first search function? (Select 2)


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More