Grid Illumination — LeetCode 1001 Python Solution
- Problem
- #1001
- Pattern
- Hash Map
- Reading time
- 5 min
- Source
- leetcode.com
The 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] = [rowi, coli] indicates that the lamp at grid[rowi][coli] is turned on.
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].
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m + q), where m and q are the lengths of the arrays \textit{lamps} and \textit{queries}, respectively |
| Space | O(n) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1001. Grid Illumination is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1001. Grid Illumination?
- LeetCode 1001. Grid Illumination is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1001. Grid Illumination?
- The Python solution on this page runs in O(m + q), where m and q are the lengths of the arrays \textit{lamps} and \textit{queries}, respectively.
- What is the space complexity of LeetCode 1001. Grid Illumination?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1001. Grid Illumination cover?
- LeetCode 1001. Grid Illumination is tagged Array and Hash Table on LeetCode.