705132. The Light Problem

Easy

Here is the Markdown blog post for the "The Light Problem" problem:

The Light Problem

Summary

The Light Problem involves finding the minimum number of lights needed to light up all points in a given grid. The problem requires a combination of logic and algorithmic thinking, making it an interesting challenge for beginners.

Detailed Explanation

To solve this problem, we will iterate through each point in the grid and count the number of lights that can be seen from that point. We then update our total count based on this count. This process is repeated until all points have been processed.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable lights to 0, which will store the minimum number of lights needed.
  2. Iterate through each row in the grid from top to bottom and for each column from left to right.
  3. For each point in the grid, initialize a variable visibleLights to 0, which will count the number of lights that can be seen from this point.
  4. Check if there are any lights to the left or above the current point. If yes, increment visibleLights.
  5. Check if there are any lights to the right or below the current point. If yes, increment visibleLights.
  6. Update the total count of lights (lights) by adding 1 and the count of visible lights.
  7. Repeat steps 2-6 until all points in the grid have been processed.

The time complexity of this solution is O(m*n), where m is the number of rows and n is the number of columns in the grid. The space complexity is O(1) as we only use a constant amount of space to store our variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class LightProblem {
    public static int minLights(int[][] grid) {
        int lights = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                int visibleLights = 0;
                if (i > 0 || j > 0) {
                    visibleLights++;
                }
                if (i < grid.length - 1 || j < grid[0].length - 1) {
                    visibleLights++;
                }
                lights += 1 + visibleLights;
            }
        }
        return lights;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.