Problem 1222

Abstract / Summary

Find all queens that can move to the king's square in one chess queen move on an empty board.

Note

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

Python 1222.py

class Solution:
    def queensAttacktheKing(self, queens: List[List[int]], king: List[int]) -> List[List[int]]:
        hashed = set(tuple([ qx, qy ]) for qx, qy in queens) # faster than linear search
        deltas = [ [ -1, -1 ], [ -1, 0 ], [ -1, +1 ],\
                   [  0, -1 ],            [  0, +1 ],\
                   [ +1, -1 ], [ +1, 0],  [ +1, +1 ] ]

        kx, ky = king
        for dx, dy in deltas:
            for i in range(1, 8):
                qx = kx + dx * i
                qy = ky + dy * i
                if (qx, qy) in hashed:
                    yield [ qx, qy ]
                    break
                if min(qx, qy) < 0 or max(qx, qy) >= 8:
                    break # out of bounds
17 lines | 736 bytes | submitted November 1, 2023 | GitHub   12% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (70k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Simulation
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 routine determines which queens on a standard 8 × 8 chessboard can directly attack the king. It examines all eight possible straight-line directions from the king’s position, stepping outward until it either encounters a queen or reaches the board edge. Queens that are the first piece encountered in a direction are produced as the result.

Data Preparation

A hash-based container is built from the list of queen coordinates. Converting each coordinate pair into a tuple and storing it in a set enables constant-time membership tests, which replaces the need for a linear scan of the queen list.

hashed = set(tuple([ qx, qy ]) for qx, qy in queens)

Direction Vectors

All eight directions a queen can move are encoded as pairs of row and column offsets. The list includes the four orthogonal directions and the four diagonals.

deltas = [ [ -1, -1 ], [ -1, 0 ], [ -1, +1 ],
           [  0, -1 ],            [  0, +1 ],
           [ +1, -1 ], [ +1, 0],  [ +1, +1 ] ]

Iterating Directions

The algorithm extracts the king’s coordinates and then iterates over each direction vector. For each direction it steps outward one square at a time, up to a maximum of seven steps (the board size minus one). The new candidate square is computed by scaling the direction offsets with the step index.

kx, ky = king
for dx, dy in deltas:
    for i in range(1, 8):
        qx = kx + dx * i
        qy = ky + dy * i

Boundary Checks

Before testing for a queen, the code verifies that the candidate square lies within the board limits. The condition uses min and max to detect any coordinate that falls below zero or exceeds the highest valid index (7). If the square is out of bounds, the inner loop terminates for that direction.

if min(qx, qy) < 0 or max(qx, qy) >= 8:
    break  # out of bounds

Yielding Result

When a queen’s coordinate appears in the pre-computed set, the algorithm yields that coordinate as an attacking queen and stops further scanning in the same direction, because any queen beyond the first would be blocked.

if (qx, qy) in hashed:
    yield [ qx, qy ]
    break

Edge Cases Handled

The implementation correctly processes the situation where a queen sits immediately adjacent to the king; the first iteration of the inner loop discovers the queen and yields it. It also gracefully handles directions that contain no queens; the loop runs until the board edge is reached, then exits without yielding. When the king is positioned on the board’s perimeter, the boundary check prevents attempts to access squares outside the valid range, ensuring the algorithm terminates cleanly for those edge positions.

Performance Optimizations

The primary optimization is the use of a hash set for queen positions, which reduces the cost of existence checks from linear to constant time. By breaking out of the inner loop as soon as a queen is found or the board edge is reached, the algorithm avoids unnecessary iterations beyond the first blocking piece. The fixed board size (8 × 8) limits the maximum number of steps per direction, keeping the overall work bounded and predictable.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big square grid that looks like a chessboard with sixty-four little boxes. Somewhere on this board sits a lonely king who wants to find his friends, the queens. To help the king look around, there is a list of all the directions he can peer into, like straight up, down, sideways, or even slanted like a slide.

The computer starts at the king and walks out in each of those eight directions one step at a time. It keeps going further and further away from the king along these lines. As it walks, it checks every single square to see if a queen is standing there waiting. The first time the computer bumps into a queen while looking in a specific direction, it remembers where she is and stops looking further down that path because that queen is blocking the view of anyone standing behind her.

If the computer walks so far that it reaches the edge of the chessboard, it knows there are no more queens to find in that direction, so it turns around to try a different way. By checking these eight paths one by one, all the nearest queens are gathered up safely.

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.41 | σ = 1.16

Complexity Analysis

not analyzed yet

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 Go TS
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
23 links | 12 authors | 7 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

6 solutions   November 1, 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