#1631

Path With Minimum Effort

Medium
ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixGraph Traversal (BFS/DFS)Binary Search
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max_diff))
Space
O(1)
O(n)
💡

Intuition

Time O(n log(max_diff))Space O(n)

The optimal approach uses a binary search combined with a graph traversal (like BFS or Dijkstra's algorithm) to efficiently find the minimum effort required. We treat the problem as finding the smallest maximum edge weight in a path from the start to the end.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define the binary search range between 0 and the maximum height difference in the grid.
  2. 2Step 2: For each mid value in the binary search, check if there exists a path from (0, 0) to (rows-1, columns-1) using only edges with a difference less than or equal to mid.
  3. 3Step 3: If a path exists, try for a smaller mid value; otherwise, increase mid.
solution.py27 lines
1from collections import deque
2
3def minEffort(heights):
4    def canReach(mid):
5        directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
6        queue = deque([(0, 0)])
7        visited = set((0, 0))
8        while queue:
9            x, y = queue.popleft()
10            if (x, y) == (len(heights) - 1, len(heights[0]) - 1):
11                return True
12            for dx, dy in directions:
13                nx, ny = x + dx, y + dy
14                if 0 <= nx < len(heights) and 0 <= ny < len(heights[0]) and (nx, ny) not in visited:
15                    if abs(heights[nx][ny] - heights[x][y]) <= mid:
16                        visited.add((nx, ny))
17                        queue.append((nx, ny))
18        return False
19
20    left, right = 0, max(max(row) for row in heights) - min(min(row) for row in heights)
21    while left < right:
22        mid = (left + right) // 2
23        if canReach(mid):
24            right = mid
25        else:
26            left = mid + 1
27    return left

Complexity note: The time complexity is O(n log(max_diff)) where n is the number of cells and max_diff is the maximum height difference in the grid. The space complexity is O(n) due to the queue used for BFS.

  • 1The problem can be visualized as a graph where each cell is a node and edges represent height differences.
  • 2Binary search helps efficiently narrow down the minimum effort required.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.