Skip to main content
← Problem catalogue Understand the pattern. Try it yourself. Review the solution. Practice this pattern →
Medium Queue / BFS Medium frequency Solution Available Practice Mode

Walls and Gates LeetCode Solution

Tags: #Array #BFS #Matrix

Approach Summary

Multi-source BFS starting from all gates (value 0) simultaneously. Empty rooms get filled with distance from nearest gate.

Practice Mode

Solve it yourself before revealing the code

DSA interviews test reasoning from brute force to optimal. Think through the constraints first.

Algorithmic Pattern

Master the Queue / BFS Pattern

View Pattern Guide →

Study the core invariant, step-by-step decision framework, and common interview traps for the Queue / BFS pattern.

Framework: Queue / BFS • Interview Prep: Tested at FAANG • Explore all Queue / BFS problems & invariants →

How to Recognize This Pattern

  • "Fill each room with distance to nearest gate"
  • Multi-source BFS beats repeated single-source BFS

Complexity Analysis

Time Complexity

O(m × n)

Space Complexity

O(m × n)

Tags

Array BFS Matrix

Frequently Asked Questions

What is the optimal time and space complexity for Walls and Gates?
The optimal solution for Walls and Gates achieves O(m × n) runtime complexity and requires O(m × n) auxiliary space. Time Complexity: O(m × n) — each element or state is traversed and evaluated in bounded amortized time without redundant reprocessing. Space Complexity: O(m × n) — allocated for auxiliary tracking structures, recursion call stack, or state caches.
How do I identify that Walls and Gates requires the Queue / BFS pattern?
In technical interviews, look for key problem signals: "Fill each room with distance to nearest gate"; Multi-source BFS beats repeated single-source BFS. Recognizing these invariants allows you to bypass naive brute-force exhaustive search in favor of Queue / BFS strategy.
What critical edge cases must be handled in Walls and Gates?
Essential edge cases to verify include: Key recognition trigger: "Fill each room with distance to nearest gate".; Constraint condition: Multi-source BFS beats repeated single-source BFS.; Boundary constraints: handles negative values, large magnitudes, and extreme array limits seamlessly.; Suboptimal inputs: runs strictly within the O(m × n) time budget without stack overflow or time limit exceeded.. Always walk through these scenarios with your interviewer before coding.
Which tech companies frequently ask Walls and Gates?
Walls and Gates is a Medium-difficulty question tagged with medium recurrence. It is actively asked in technical screening and onsite interview loops at Facebook, Amazon.
Buy me a coffee
Daily Practice
0/0