Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #505: The Maze II

In this guide, we solve Leetcode #505 The Maze II 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.

Leetcode

Problem Statement

There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall.

Quick Facts

  • Difficulty: Medium
  • Premium: Yes
  • Tags: Depth-First Search, Breadth-First Search, Graph, Array, Matrix, Shortest Path, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

Example

Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4] Output: 12 Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right. The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

Python Solution

class Solution: def shortestDistance( self, maze: List[List[int]], start: List[int], destination: List[int] ) -> int: m, n = len(maze), len(maze[0]) dirs = (-1, 0, 1, 0, -1) si, sj = start di, dj = destination q = deque([(si, sj)]) dist = [[inf] * n for _ in range(m)] dist[si][sj] = 0 while q: i, j = q.popleft() for a, b in pairwise(dirs): x, y, k = i, j, dist[i][j] while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0: x, y, k = x + a, y + b, k + 1 if k < dist[x][y]: dist[x][y] = k q.append((x, y)) return -1 if dist[di][dj] == inf else dist[di][dj]

Complexity

The time complexity is O(n log n). 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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy