Grid Illumination - Problem

There is a 2D grid of size n x n where each cell of this grid has a lamp that is initially turned off.

You are given a 2D array of lamp positions lamps, where lamps[i] = [row_i, col_i] indicates that the lamp at grid[row_i][col_i] is turned on. Even if the same lamp is listed more than once, it is turned on.

When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal.

You are also given another 2D array queries, where queries[j] = [row_j, col_j]. For the j-th query, determine whether grid[row_j][col_j] is illuminated or not. After answering the j-th query, turn off the lamp at grid[row_j][col_j] and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with grid[row_j][col_j].

Return an array of integers ans, where ans[j] should be 1 if the cell in the j-th query was illuminated, or 0 if the lamp was not.

Input & Output

Example 1 — Basic Illumination
$ Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
💡 Note: Query [1,1]: Lamp at [0,0] illuminates same main diagonal (0-0 = 1-1). Query [1,0]: Lamp at [0,0] illuminates same column 0, but after first query, nearby lamps are turned off.
Example 2 — Multiple Lamps
$ Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,1]]
Output: [1,1]
💡 Note: First query [1,1]: Both lamps illuminate this position. Second query [1,1]: Lamps were turned off in 3x3 area, but lamp at [4,4] is still active and illuminates via diagonal.
Example 3 — No Illumination
$ Input: n = 5, lamps = [[0,0]], queries = [[4,4]]
Output: [0]
💡 Note: Query [4,4]: Lamp at [0,0] does not illuminate [4,4] (different row, column, and diagonals).

Constraints

  • 1 ≤ n ≤ 109
  • 0 ≤ lamps.length ≤ 20000
  • 0 ≤ queries.length ≤ 20000
  • lamps[i].length == 2
  • 0 ≤ rowi, coli < n

Visualization

Tap to expand
Grid Illumination Problem OverviewLL?Step 1: LampsLL1Step 2: IlluminatedL0Step 3: Turn OffQuery (1,1): Illuminated by lamp at (0,0) via same columnAfter query: Turn off lamp at (0,0) and all neighbors in 3×3 area
Understanding the Visualization
1
Input
Grid with lamps at specific positions
2
Illumination
Each lamp lights up its row, column, and diagonals
3
Query & Turn Off
Check illumination, then turn off nearby lamps
Key Takeaway
🎯 Key Insight: Use hash maps to count illuminating lines (rows/columns/diagonals) for O(1) query time
Asked in
Google 15 Amazon 8 Microsoft 6
25.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen