Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king.
You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king.
Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
Example 1:
Input: queens = [[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]], king = [0,0] Output: [[0,1],[1,0],[3,3]] Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Example 2:
Input: queens = [[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]], king = [3,3] Output: [[2,2],[3,4],[4,4]] Explanation: The diagram above shows the three queens that can directly attack the king and the three queens that cannot attack the king (i.e., marked with red dashes).
Constraints:
1 <= queens.length < 64queens[i].length == king.length == 20 <= xQueeni, yQueeni, xKing, yKing < 8Problem summary: On a 0-indexed 8 x 8 chessboard, there can be multiple black queens and one white king. You are given a 2D integer array queens where queens[i] = [xQueeni, yQueeni] represents the position of the ith black queen on the chessboard. You are also given an integer array king of length 2 where king = [xKing, yKing] represents the position of the white king. Return the coordinates of the black queens that can directly attack the king. You may return the answer in any order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[0,1],[1,0],[4,0],[0,4],[3,3],[2,4]] [0,0]
[[0,0],[1,1],[2,2],[3,4],[3,5],[4,4],[4,5]] [3,3]
minimum-moves-to-capture-the-queen)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1222: Queens That Can Attack the King
class Solution {
public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
final int n = 8;
var s = new boolean[n][n];
for (var q : queens) {
s[q[0]][q[1]] = true;
}
List<List<Integer>> ans = new ArrayList<>();
for (int a = -1; a <= 1; ++a) {
for (int b = -1; b <= 1; ++b) {
if (a != 0 || b != 0) {
int x = king[0] + a, y = king[1] + b;
while (x >= 0 && x < n && y >= 0 && y < n) {
if (s[x][y]) {
ans.add(List.of(x, y));
break;
}
x += a;
y += b;
}
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #1222: Queens That Can Attack the King
func queensAttacktheKing(queens [][]int, king []int) (ans [][]int) {
n := 8
s := [8][8]bool{}
for _, q := range queens {
s[q[0]][q[1]] = true
}
for a := -1; a <= 1; a++ {
for b := -1; b <= 1; b++ {
if a != 0 || b != 0 {
x, y := king[0]+a, king[1]+b
for 0 <= x && x < n && 0 <= y && y < n {
if s[x][y] {
ans = append(ans, []int{x, y})
break
}
x += a
y += b
}
}
}
}
return
}
# Accepted solution for LeetCode #1222: Queens That Can Attack the King
class Solution:
def queensAttacktheKing(
self, queens: List[List[int]], king: List[int]
) -> List[List[int]]:
n = 8
s = {(i, j) for i, j in queens}
ans = []
for a in range(-1, 2):
for b in range(-1, 2):
if a or b:
x, y = king
while 0 <= x + a < n and 0 <= y + b < n:
x, y = x + a, y + b
if (x, y) in s:
ans.append([x, y])
break
return ans
// Accepted solution for LeetCode #1222: Queens That Can Attack the King
struct Solution;
use std::collections::HashSet;
type Point = Vec<i32>;
struct Chessboard {
directions: Vec<Point>,
queens: HashSet<Point>,
king: Point,
}
impl Chessboard {
fn new(queens_vec: Vec<Point>, king: Point) -> Self {
let directions: Vec<Point> = vec![
vec![1, 0],
vec![-1, 0],
vec![0, 1],
vec![0, -1],
vec![1, 1],
vec![-1, 1],
vec![1, -1],
vec![-1, -1],
];
let mut queens: HashSet<Point> = HashSet::new();
for queen in queens_vec {
queens.insert(queen);
}
Chessboard {
directions,
queens,
king,
}
}
fn contains(&self, point: &[i32]) -> bool {
point[0] >= 0 && point[1] >= 0 && point[0] < 8 && point[1] < 8
}
fn attack(&self, i: usize, step: i32) -> Point {
let direction = &self.directions[i];
let king = &self.king;
vec![king[0] + direction[0] * step, king[1] + direction[1] * step]
}
}
impl Solution {
fn queens_attackthe_king(queens: Vec<Vec<i32>>, king: Vec<i32>) -> Vec<Vec<i32>> {
let mut res = vec![];
let cb = Chessboard::new(queens, king);
for i in 0..8 {
let mut step = 1;
loop {
let p = cb.attack(i, step);
if cb.contains(&p) {
if cb.queens.contains(&p) {
res.push(p);
break;
} else {
step += 1;
}
} else {
break;
}
}
}
res
}
}
#[test]
fn test() {
let queens = vec_vec_i32![[0, 1], [1, 0], [4, 0], [0, 4], [3, 3], [2, 4]];
let king = vec![0, 0];
let mut res = vec_vec_i32![[0, 1], [1, 0], [3, 3]];
let mut ans = Solution::queens_attackthe_king(queens, king);
res.sort();
ans.sort();
assert_eq!(ans, res);
let queens = vec_vec_i32![[0, 0], [1, 1], [2, 2], [3, 4], [3, 5], [4, 4], [4, 5]];
let king = vec![3, 3];
let mut res = vec_vec_i32![[2, 2], [3, 4], [4, 4]];
let mut ans = Solution::queens_attackthe_king(queens, king);
res.sort();
ans.sort();
assert_eq!(ans, res);
let queens = vec_vec_i32![
[5, 6],
[7, 7],
[2, 1],
[0, 7],
[1, 6],
[5, 1],
[3, 7],
[0, 3],
[4, 0],
[1, 2],
[6, 3],
[5, 0],
[0, 4],
[2, 2],
[1, 1],
[6, 4],
[5, 4],
[0, 0],
[2, 6],
[4, 5],
[5, 2],
[1, 4],
[7, 5],
[2, 3],
[0, 5],
[4, 2],
[1, 0],
[2, 7],
[0, 1],
[4, 6],
[6, 1],
[0, 6],
[4, 3],
[1, 7]
];
let king = vec![3, 4];
let mut res = vec_vec_i32![[2, 3], [1, 4], [1, 6], [3, 7], [4, 3], [5, 4], [4, 5]];
let mut ans = Solution::queens_attackthe_king(queens, king);
res.sort();
ans.sort();
assert_eq!(ans, res);
}
// Accepted solution for LeetCode #1222: Queens That Can Attack the King
function queensAttacktheKing(queens: number[][], king: number[]): number[][] {
const n = 8;
const s: boolean[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => false));
queens.forEach(([x, y]) => (s[x][y] = true));
const ans: number[][] = [];
for (let a = -1; a <= 1; ++a) {
for (let b = -1; b <= 1; ++b) {
if (a || b) {
let [x, y] = [king[0] + a, king[1] + b];
while (x >= 0 && x < n && y >= 0 && y < n) {
if (s[x][y]) {
ans.push([x, y]);
break;
}
x += a;
y += b;
}
}
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.