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.
💡 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.
💡 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).
The key insight is to use hash maps to count illuminating lines instead of checking individual lamps. Track counts for rows, columns, and both diagonals. A cell is illuminated if any of its lines has count > 0. Best approach uses hash maps with Time: O(l + q), Space: O(l).
Common Approaches
✓
Optimized
⏱️ Time: N/A
Space: N/A
Brute Force
⏱️ Time: O(q × l)
Space: O(l)
For each query position, iterate through all lamps and check if any lamp is in the same row, column, or diagonal. After answering, remove all lamps in the 3x3 area around the query.
Hash Map Optimization
⏱️ Time: O(l + q)
Space: O(l)
Track counts of lamps in each row, column, and diagonal using hash maps. A cell is illuminated if any of its lines has count > 0. Update counts efficiently when turning off lamps.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LAMPS 20000
#define MAX_QUERIES 20000
#define HASH_SIZE 100007
static int rows[HASH_SIZE];
static int cols[HASH_SIZE];
static int diag1[HASH_SIZE];
static int diag2[HASH_SIZE];
static int lamp_pairs[MAX_LAMPS][2];
static int lamp_count = 0;
int hash_func(int key) {
if (key < 0) key = -key + HASH_SIZE/2;
return key % HASH_SIZE;
}
int has_lamp(int r, int c) {
for (int i = 0; i < lamp_count; i++) {
if (lamp_pairs[i][0] == r && lamp_pairs[i][1] == c) {
return 1;
}
}
return 0;
}
void remove_lamp(int r, int c) {
for (int i = 0; i < lamp_count; i++) {
if (lamp_pairs[i][0] == r && lamp_pairs[i][1] == c) {
// Move last lamp to this position
lamp_pairs[i][0] = lamp_pairs[lamp_count-1][0];
lamp_pairs[i][1] = lamp_pairs[lamp_count-1][1];
lamp_count--;
return;
}
}
}
int parse_array(char* line, int arr[][2]) {
int count = 0;
if (strcmp(line, "[]") == 0) return 0;
char* ptr = line;
while ((ptr = strchr(ptr, '[')) != NULL) {
if (ptr == line) {
ptr++;
continue;
}
ptr++; // skip '['
char* end = strchr(ptr, ']');
if (end == NULL) break;
*end = '\0';
char* comma = strchr(ptr, ',');
if (comma != NULL) {
*comma = '\0';
arr[count][0] = atoi(ptr);
arr[count][1] = atoi(comma + 1);
count++;
}
*end = ']';
ptr = end + 1;
}
return count;
}
int* solution(int n, int lamps[][2], int lamps_size, int queries[][2], int queries_size) {
memset(rows, 0, sizeof(rows));
memset(cols, 0, sizeof(cols));
memset(diag1, 0, sizeof(diag1));
memset(diag2, 0, sizeof(diag2));
lamp_count = 0;
// Add all lamps and update counters
for (int i = 0; i < lamps_size; i++) {
int r = lamps[i][0], c = lamps[i][1];
if (!has_lamp(r, c)) {
lamp_pairs[lamp_count][0] = r;
lamp_pairs[lamp_count][1] = c;
lamp_count++;
rows[hash_func(r)]++;
cols[hash_func(c)]++;
diag1[hash_func(r - c)]++;
diag2[hash_func(r + c)]++;
}
}
int* result = malloc(queries_size * sizeof(int));
for (int i = 0; i < queries_size; i++) {
int qr = queries[i][0], qc = queries[i][1];
// Check if cell is illuminated
int illuminated = (rows[hash_func(qr)] > 0 || cols[hash_func(qc)] > 0 ||
diag1[hash_func(qr - qc)] > 0 || diag2[hash_func(qr + qc)] > 0);
result[i] = illuminated ? 1 : 0;
// Turn off lamps in 3x3 area
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = qr + dr, nc = qc + dc;
if (has_lamp(nr, nc)) {
remove_lamp(nr, nc);
rows[hash_func(nr)]--;
cols[hash_func(nc)]--;
diag1[hash_func(nr - nc)]--;
diag2[hash_func(nr + nc)]--;
}
}
}
}
return result;
}
int main() {
char line[100000];
fgets(line, sizeof(line), stdin);
int n = atoi(line);
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0;
static int lamps[MAX_LAMPS][2];
int lamps_size = parse_array(line, lamps);
fgets(line, sizeof(line), stdin);
line[strcspn(line, "\n")] = 0;
static int queries[MAX_QUERIES][2];
int queries_size = parse_array(line, queries);
int* result = solution(n, lamps, lamps_size, queries, queries_size);
printf("[");
for (int i = 0; i < queries_size; i++) {
printf("%d", result[i]);
if (i < queries_size - 1) printf(",");
}
printf("]\n");
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
25.0K Views
MediumFrequency
~35 minAvg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.