Member-only story

Solution for Leetcode problem 1222: Queens that can attack the king

Pierre-Marie Poitevin
2 min readOct 13, 2019

--

In this problem, the question is which queen can attack the king given all the queens’ and king’s positions.

Problem statement

I took the simple approach of:

  • Go from the king’s position
  • Look in all directions one by one
  • For each direction, I move through the positions one by one from the king until the position is occupied by a queen or the position is outside of the chess board
  • To ease the search though the queens’ position array, I hashed the positions to integer x*8 + y, so the position lookup is constant time.

Technically, since the board size is constant, and queen[][] size is constant, there is no need for complexity analysis; but for a board N*N and a queens’ array of size M, the time complexity becomes O(N + M).

Solution:

class Solution {
enum Step {

R(1, 0),
L(-1, 0),
U(0, -1),
D(0, 1),
RU(1, -1),
RD(1, 1),
LU(-1, -1),
LD(-1, 1);

int x;
int y;

Step(int a, int b) {
x = a;
y = b;
}

int[] newPos(int[] pos) {
int[] res = new int[2];
res[0] = pos[0] + x;
res[1] =…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet