Problem 1812

Abstract / Summary

Determine if a chessboard square is white or black based on its coordinates.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1812.py

class Solution:
    def squareIsWhite(self, coordinates: str) -> bool:
        return (ord(coordinates[0]) + ord(coordinates[1])) & 1
3 lines | 137 bytes | submitted December 27, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 80% (100k+ submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a single method squareIsWhite inside a Solution class. Its purpose is to decide whether a given chessboard coordinate corresponds to a white square. The logic is compact: it converts the two characters of the coordinate to their ASCII codes, adds them together, and checks the parity of the result using a bitwise AND with 1. The parity directly maps to the color pattern of a standard chessboard, allowing the method to return a Boolean value without any conditional statements.

Key Steps

Step 1 - Extract characters from the input string

The method accesses the first and second characters of the coordinates argument by indexing the string.

coordinates[0]   # column letter, e.g., 'a'
coordinates[1]   # row digit, e.g., '1'

Step 2 - Convert characters to numeric codes

ord transforms each character into its integer Unicode (ASCII for the relevant range) representation.

ord(coordinates[0])
ord(coordinates[1])

Step 3 - Compute combined parity

The two integer codes are summed, and the least-significant bit is isolated with the expression & 1. The result is 0 for even sums and 1 for odd sums.

(ord(coordinates[0]) + ord(coordinates[1])) & 1

Step 4 - Return the Boolean result

In Python, any non-zero integer evaluates to True in a Boolean context, while 0 evaluates to False. The method returns the integer produced by the parity test directly, relying on this implicit conversion.

return (ord(coordinates[0]) + ord(coordinates[1])) & 1

Edge Cases Handled

The algorithm works correctly for any two-character string where the first character is a letter and the second is a digit, because the parity of the ASCII codes follows the same alternating pattern as a chessboard. If the input contains characters outside the typical 'a'-'h' and '1'-'8' ranges, the parity calculation still yields a deterministic Boolean, ensuring the function never raises an exception due to unexpected character values. The method also gracefully handles lower-case and upper-case letters, as the ASCII codes for 'A'-'Z' and 'a'-'z' differ by a constant offset that does not affect the parity relationship.

Performance Optimizations Observed

The implementation avoids any branching, loops, or data structures. By using direct arithmetic (+) and a single bitwise operation (& 1), the code executes in constant time with minimal CPU cycles. The use of ord eliminates the need for dictionary lookups or conditional mapping tables, reducing memory accesses. Returning the raw integer result leverages Python’s built-in truthiness conversion, avoiding an explicit comparison or cast. All these choices keep the function lightweight and highly efficient for repeated calls.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a chessboard with its beautiful black and white squares. This code acts like a tiny detective that looks at any square on that board to help figure out its color. The piece of information received is a little label, like a secret code for a square, such as a one and an a. The code looks at the little letter and the number in that label. Every character has a secret number hidden inside it, and the code adds those two numbers together. When the two numbers are added up, they make a sum. If that sum is an odd number, it means the square is white. If it is an even number, it means the square is black. The code uses a special trick with the numbers to check if that sum is odd or even. Every time a new square is given, the code repeats this work to find the answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.37 | σ = 2.02

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS C Go Rust TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
YuriSpiridonov Python
30 links | 16 authors | 10 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

5 solutions   December 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality