KatInterview

Chess Queen Line-of-Sight Attack Counting

Arrays & HashingModel answer
MediumModel answerArrays & Hashinggeometryhash-mapbinary-search

Last 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 placed
  • points: 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) tuples
  • points: list of (x, y) tuples
  • obstacles: 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?