Leetcode #1001: Grid Illumination
In this guide, we solve Leetcode #1001 Grid Illumination in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Hash Table
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
Explanation: We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid[0][0] then turning on the lamp at grid[4][4].
The 0th query asks if the lamp at grid[1][1] is illuminated or not (the blue square). It is illuminated, so set ans[0] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid[1][0] is illuminated or not (the blue square). It is not illuminated, so set ans[1] = 0. Then, we turn off all lamps in the red rectangle.
Python Solution
class Solution:
def gridIllumination(
self, n: int, lamps: List[List[int]], queries: List[List[int]]
) -> List[int]:
s = {(i, j) for i, j in lamps}
row, col, diag1, diag2 = Counter(), Counter(), Counter(), Counter()
for i, j in s:
row[i] += 1
col[j] += 1
diag1[i - j] += 1
diag2[i + j] += 1
ans = [0] * len(queries)
for k, (i, j) in enumerate(queries):
if row[i] or col[j] or diag1[i - j] or diag2[i + j]:
ans[k] = 1
for x in range(i - 1, i + 2):
for y in range(j - 1, j + 2):
if (x, y) in s:
s.remove((x, y))
row[x] -= 1
col[y] -= 1
diag1[x - y] -= 1
diag2[x + y] -= 1
return ans
Complexity
The time complexity is , where and are the lengths of the arrays and , respectively. The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.