Determine Color of a Chessboard Square - Problem

You are given coordinates, a string that represents the coordinates of a square on a chessboard.

A chessboard is an 8x8 grid where squares alternate between white and black colors. The bottom-left square a1 is a dark (black) square.

Return true if the square is white, and false if the square is black.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.

Input & Output

Example 1 — Corner Square
$ Input: coordinates = "a1"
Output: false
💡 Note: Square a1 is at column 1, row 1. Sum = 1 + 1 = 2 (even), so it's black. Return false.
Example 2 — White Square
$ Input: coordinates = "h3"
Output: true
💡 Note: Square h3 is at column 8, row 3. Sum = 8 + 3 = 11 (odd), so it's white. Return true.
Example 3 — Adjacent Square
$ Input: coordinates = "c7"
Output: false
💡 Note: Square c7 is at column 3, row 7. Sum = 3 + 7 = 10 (even), so it's black. Return false.

Constraints

  • coordinates.length == 2
  • coordinates[0] is a letter from 'a' to 'h'
  • coordinates[1] is a digit from '1' to '8'

Visualization

Tap to expand
Chessboard Square Color - XOR Approach INPUT a1 a b c d 1 2 3 4 coordinates = "a1" Letter: 'a', Number: '1' a1 is bottom-left (dark) ALGORITHM STEPS 1 Extract Values col = 'a' - 'a' = 0 row = '1' - '1' = 0 2 XOR Operation result = col XOR row result = 0 XOR 0 = 0 col: 0 = 0b0000 row: 0 = 0b0000 XOR: 0b0000 = 0 3 Check Parity isWhite = (result % 2 == 1) 4 Evaluate 0 % 2 = 0 (even) 0 != 1, so false FINAL RESULT a1 DARK Output: false Square a1 is BLACK XOR result = 0 (even) Even = Dark square Return: false Key Insight: The XOR of column and row indices reveals the square color pattern. When (col XOR row) is ODD, the square is WHITE. When EVEN, it's BLACK. This works because adjacent squares differ by 1 in either row or column, flipping the XOR parity -- exactly matching the alternating pattern! TutorialsPoint - Determine Color of a Chessboard Square | XOR Bit Manipulation Approach
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~5 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen