Chess Queen Line-of-Sight Attack Counting
Arrays & HashingModel answerLast updated
Calculate how many chess queens can attack each query position, first without obstacles, then accounting for blocking pieces on the board.
You're working with an infinite 2D grid where each cell has integer coordinates (x, y).
You're given:
queens: a list of coordinates where queens are placedpoints: a list of query coordinates
A queen moves like in chess: it can reach any cell along its row, column, or either diagonal (8 total directions).
Part 1: Open Board
For each query point in points, determine how many queens can reach it.
A queen at position q can reach point p if they share the same row, column, or diagonal line.
Return an array where the i-th element is the count of queens that can reach points[i].
Part 2: Obstacles Block Movement
You're now also given:
obstacles: a list of coordinates containing blocking pieces
An obstacle blocks a queen's path. A queen can reach point p only if no obstacle lies strictly between them on the connecting line.
Important clarifications:
- Queens don't block each other
- A queen standing exactly at a query point doesn't count as reaching it
- An obstacle at the same position as the query point doesn't block incoming paths
- An obstacle at the same position as a queen doesn't block that queen
Return the same format: counts for each query point.
Input Format
queens: list of(x, y)tuplespoints: list of(x, y)tuplesobstacles: list of(x, y)tuples (Part 2 only)
Constraints
1 ≤ len(queens), len(points), len(obstacles) ≤ 200,000- Coordinates are 32-bit signed integers
- Target complexity:
O((Q + R + P) log(Q + R))for Part 2
Example
queens = [(0, 0), (5, 5)]
points = [(2, 2), (3, 0)]
obstacles = [(1, 1)]
Part 1 answer: [2, 1]
- (2,2): both queens reach it via diagonals
- (3,0): only (0,0) reaches it via row
Part 2 answer: [1, 1]
- (2,2): only (5,5) reaches it; (0,0) is blocked by obstacle at (1,1)
- (3,0): still (0,0), no obstacles on that row
Hints
Hint 1
Every point lies on exactly four lines: one horizontal, one vertical, and two diagonal. Which mathematical expressions uniquely identify these lines?
Hint 2
For Part 1, you can use hash maps to group queens by their line membership. How do you avoid counting a queen that sits exactly on the query point?
Hint 3
For Part 2, obstacles split each line into segments. On each side of the query point, which obstacle matters most? How can you find the queens between the query point and that obstacle?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Insight: Line Identification
Any position (x, y) belongs to exactly four lines that a queen uses:
| Line Type | Identifier | Position Coordinate |
|---|---|---|
| Horizontal | y | x |
| Vertical | x | y |
| Diagonal (↘) | x - y | x |
| Diagonal (↙) | x + y | x |
Two different lines through point p intersect only at p itself. Therefore, a queen not at p shares exactly one line with it, preventing double-counting.
Part 1: No Obstacles
Build four hash maps counting queens per line identifier. For each query point, sum the counts from its four lines, then subtract queens positioned exactly at that point (which match all four lines but shouldn't count).
Time Complexity: O(Q + P) where Q = queens, P = query points
Space Complexity: O(Q)
Part 2: With Obstacles
Obstacles divide each line into segments. Consider one line through query point p with position t:
- Left attacking zone: Queens between the nearest left obstacle and
t - Right attacking zone: Queens between
tand the nearest right obstacle
Let rL = position of nearest obstacle with position < t (or -∞ if none exists)
Let rR = position of nearest obstacle with position > t (or +∞ if none exists)
Queens that can reach p from the left have positions in [rL, t) (closed at rL because a queen sharing a cell with an obstacle isn't blocked by it).
Queens from the right have positions in (t, rR].
Implementation:
- Group queens and obstacles by line identifier
- Sort positions within each line
- For each query, use binary search to count queens in valid intervals on all four lines
Time Complexity: O((Q + R) log(Q + R) + P log(Q + R)) where R = obstacles
Space Complexity: O(Q + R)
Edge Cases
- No queens on a line: contributes 0
- Obstacle at query point: doesn't block (not strictly between)
- Multiple obstacles on one side: only nearest matters
- Queen and obstacle share a cell: queen still reaches through that position
- Duplicate queens: each counts separately
- Integer overflow:
x + yandx - ycan exceed 32-bit range; use 64-bit keys in languages like C++/Java
Common Mistakes
- Counting a queen at the query point: Must subtract these explicitly in Part 1
- Wrong interval boundaries: Using open intervals at obstacles when they should be closed
- Forgetting diagonal types: The two diagonals have different formulas (
x-yvsx+y) - Inefficient obstacle checking: Checking all obstacles instead of just the nearest ones
- Integer overflow: Not using long integers for coordinate sums/differences
Code
from bisect import bisect_left, bisect_right
from collections import defaultdict
from typing import List, Tuple
Point = Tuple[int, int]
def compute_lines(x: int, y: int):
"""Generate (line_id, position) for the 4 lines through (x, y)."""
yield ('row', y), x
yield ('col', x), y
yield ('diag', x - y), x
yield ('anti', x + y), x
def count_reachable_no_obstacles(queens: List[Point],
points: List[Point]) -> List[int]:
"""Part 1: count queens that can reach each point."""
line_counts = defaultdict(int)
exact_position = defaultdict(int)
for x, y in queens:
for line_id, _ in compute_lines(x, y):
line_counts[line_id] += 1
exact_position[(x, y)] += 1
result = []
for x, y in points:
total = sum(line_counts[line_id] for line_id, _ in compute_lines(x, y))
# Subtract queens exactly at this point (matched all 4 lines)
total -= 4 * exact_position.get((x, y), 0)
result.append(total)
return result
def count_reachable_with_obstacles(queens: List[Point],
points: List[Point],
obstacles: List[Point]) -> List[int]:
"""Part 2: count queens that can reach each point with blocking obstacles."""
queens_by_line = defaultdict(list)
obstacles_by_line = defaultdict(list)
for x, y in queens:
for line_id, pos in compute_lines(x, y):
queens_by_line[line_id].append(pos)
for x, y in obstacles:
for line_id, pos in compute_lines(x, y):
obstacles_by_line[line_id].append(pos)
# Sort all positions for binary search
for positions in queens_by_line.values():
positions.sort()
for positions in obstacles_by_line.values():
positions.sort()
result = []
for x, y in points:
count = 0
for line_id, target_pos in compute_lines(x, y):
queen_positions = queens_by_line.get(line_id)
if not queen_positions:
continue
obstacle_positions = obstacles_by_line.get(line_id, [])
# Left side: find nearest obstacle < target_pos
left_obstacle_idx = bisect_left(obstacle_positions, target_pos) - 1
left_bound = obstacle_positions[left_obstacle_idx] if left_obstacle_idx >= 0 else float('-inf')
# Count queens in [left_bound, target_pos)
count += bisect_left(queen_positions, target_pos) - bisect_left(queen_positions, left_bound)
# Right side: find nearest obstacle > target_pos
right_obstacle_idx = bisect_right(obstacle_positions, target_pos)
right_bound = obstacle_positions[right_obstacle_idx] if right_obstacle_idx < len(obstacle_positions) else float('inf')
# Count queens in (target_pos, right_bound]
count += bisect_right(queen_positions, right_bound) - bisect_right(queen_positions, target_pos)
result.append(count)
return result
Verification: With queens = [(0,0), (4,0)], obstacles = [(2,0)], points = [(3,0)]:
- Query position 3 on the row line
- Left bound: obstacle at position 2, no queens in [2, 3)
- Right bound: no obstacle, queen at 4 is in (3, ∞)
- Answer: 1 (only the queen at x=4 reaches x=3)
This correctly shows the queen at (0,0) is blocked.