Leetcode 1812: Determine Color of a Chessboard Square

grid47
grid47
Exploring patterns and algorithms
May 9, 2024 5 min read

You are given the coordinates of a square on a chessboard. The coordinate is represented as a string where the first character is a letter representing the column (‘a’ to ‘h’) and the second character is a number representing the row (‘1’ to ‘8’). Determine if the square is white or black. A square is white if the sum of its row and column is even, and black if it is odd.
Problem
Approach
Steps
Complexity
Input: The input consists of a string with two characters, where the first character represents the column ('a' to 'h') and the second character represents the row ('1' to '8').
Example: coordinates = "b2"
Constraints:
• coordinates.length == 2
• 'a' <= coordinates[0] <= 'h'
• '1' <= coordinates[1] <= '8'
Output: Return true if the square is white, and false if the square is black.
Example: Output: true
Constraints:
• The output should be a boolean indicating whether the square is white (true) or black (false).
Goal: To determine if the square represented by the input coordinates is white or black.
Steps:
• Convert the column letter to a numeric value (a = 1, b = 2, ..., h = 8).
• Convert the row number from a character to an integer.
• Sum the column and row values.
• If the sum is even, the square is white; if the sum is odd, the square is black.
Goal: The input coordinates will always be valid, and the square is always within the bounds of the chessboard.
Steps:
• The string `coordinates` will always have length 2.
• The column will always be between 'a' and 'h'.
• The row will always be between '1' and '8'.
Assumptions:
• The input will always represent a valid square on the chessboard.
• The function needs to return a boolean indicating whether the square is white or black.
Input: coordinates = "b2"
Explanation: The column 'b' corresponds to the value 2, and the row '2' is also 2. The sum of 2 + 2 = 4, which is even, so the square is black (output is false).

Input: coordinates = "d5"
Explanation: The column 'd' corresponds to the value 4, and the row '5' is 5. The sum of 4 + 5 = 9, which is odd, so the square is white (output is true).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus