Check if Two Chessboard Squares Have the Same Color - Problem

You are given two strings, coordinate1 and coordinate2, representing the coordinates of a square on an 8 x 8 chessboard.

Return true if these two squares have the same color and false otherwise.

The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first (indicating its column), and the number second (indicating its row).

Note: On a chessboard, squares alternate between light and dark colors. Square 'a1' is dark, and colors alternate from there.

Input & Output

Example 1 — Adjacent Squares
$ Input: coordinate1 = "a1", coordinate2 = "c3"
Output: true
💡 Note: Both squares are dark: a1 (1+1=2, even) and c3 (3+3=6, even) have same parity
Example 2 — Different Colors
$ Input: coordinate1 = "a1", coordinate2 = "h3"
Output: false
💡 Note: a1 is dark (1+1=2, even) while h3 is light (8+3=11, odd), different colors
Example 3 — Same Row Different Color
$ Input: coordinate1 = "a1", coordinate2 = "b1"
Output: false
💡 Note: Adjacent squares in same row: a1 (sum=2, even) vs b1 (sum=3, odd) have different colors

Constraints

  • coordinate1.length == 2
  • coordinate2.length == 2
  • 'a' ≤ coordinate1[0], coordinate2[0] ≤ 'h'
  • '1' ≤ coordinate1[1], coordinate2[1] ≤ '8'

Visualization

Tap to expand
Chessboard Same Color Check INPUT a1 c3 a b c d 1 2 3 4 coord1="a1" coord2="c3" Both DARK squares shown on board a1 is always DARK ALGORITHM STEPS 1 Extract coordinates col1='a', row1='1' col2='c', row2='3' 2 Convert to numbers 'a'=1, '1'=1 (sum=2) 'c'=3, '3'=3 (sum=6) 3 Check parity sum1 % 2 = 2 % 2 = 0 sum2 % 2 = 6 % 2 = 0 4 Compare parities Both are EVEN (0=0) Same parity = Same color Formula: (col + row) % 2 == same? FINAL RESULT a1 DARK = c3 DARK Calculation: a1: (1+1)%2 = 0 c3: (3+3)%2 = 0 0 == 0 (MATCH!) Output: true Both squares are the SAME color OK Key Insight: On a chessboard, the color of a square depends on the parity (odd/even) of (column + row). If both coordinates have the same parity sum, they share the same color. EVEN sum = DARK, ODD sum = LIGHT. TutorialsPoint - Check if Two Chessboard Squares Have the Same Color | Optimal Solution O(1)
Asked in
Apple 15 Google 12
30.0K Views
Medium Frequency
~5 min Avg. Time
856 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