Check if Two Chessboard Squares Have the Same Color

Ah, the classic chessboard problem! You know, the one that makes you question your entire existence as you ponder whether two squares on a chessboard are the same color. It’s like asking if your neighbor’s cat is secretly plotting world domination. Spoiler alert: it probably is. But let’s focus on the chessboard for now.

Problem Description

In this problem, you are given two coordinates on a chessboard, and your task is to determine if the squares at those coordinates are of the same color. The chessboard is colored in a checkerboard pattern, meaning that adjacent squares are of different colors. So, if you have a square at (1, 1) and another at (1, 2), one is black and the other is white. It’s like trying to figure out if your friend’s shirt matches their pants—sometimes it does, and sometimes it’s a fashion disaster.

Solution in Python


class Solution:
    def checkTwoChessboards(self, coordinate1: str, coordinate2: str) -> bool:
        def squareIsWhite(coordinate: str) -> bool:
            letter, digit = coordinate
            return ord(letter) % 2 != int(digit) % 2

        return squareIsWhite(coordinate1) == squareIsWhite(coordinate2)

Approach

The approach here is as simple as it gets. The function squareIsWhite checks if a square is white based on its coordinates. It does this by checking the parity (odd or even) of the letter and digit. If both are either odd or even, the square is black; otherwise, it’s white. The main function then compares the colors of the two squares. If they match, you get a big fat True; if not, you get False. It’s like a color-matching game, but with less glitter and more logic.

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1)
Space Complexity O(1)

Real-World Example

Imagine you’re at a party, and you see two people wearing the same color shirt. You might think, “Wow, they must be best friends!” But then you realize one is wearing a blue shirt and the other a navy blue shirt. They’re not the same! Similarly, in our chessboard problem, we’re just trying to figure out if two squares are best friends (the same color) or just acquaintances (different colors).

Similar Problems

If you enjoyed this problem, you might want to check out these similar ones: