Check if Two Chessboard Squares Have the Same Color

Problem Description

Ah, the classic chessboard dilemma! You know, the one where you’re trying to figure out if two squares are the same color. It’s like trying to decide if your friend’s new haircut is a “yes” or a “no.” Spoiler alert: it’s always a “no.”

In this problem, you’re given two coordinates on a chessboard (like “A1” or “C3”), and you need to determine if both squares are the same color. The chessboard alternates colors, so if one square is white, the other could be black, and vice versa. It’s a simple game of checkers, but with a twist!

Code Solution


class Solution {
 public:
  bool checkTwoChessboards(string coordinate1, string coordinate2) {
    return squareIsWhite(coordinate1) == squareIsWhite(coordinate2);
  }

 private:
  bool squareIsWhite(const string& coordinates) {
    const char letter = coordinates[0];
    const char digit = coordinates[1];
    return letter % 2 != digit % 2;
  }
};

Approach

The function checkTwoChessboards checks if both squares are the same color by calling the helper function squareIsWhite. This helper function determines the color of a square based on its coordinates. It uses the modulo operator to check if the sum of the letter and digit indices is even or odd. If they are the same, the squares are the same color; if not, they are different.

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 spot two friends wearing the same color shirt. You might think, “Are they on the same team, or did they just coordinate their outfits?” This problem is just like that! You’re checking if two squares on a chessboard are dressed in the same color. If they are, great! If not, well, someone needs a fashion intervention.

Similar Problems

If you enjoyed this problem, you might also like these: