Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 64 Minimum Path Sum - Implementation

Complete solution

You can modify the input grid in-place to save space. Or use a 1D (one-dimensional) array since you only need the previous row. Fill left-to-right, top-to-bottom. The order matters because each cell depends on cells above and to the left. Time: O(mn)O(mn), Space: O(1)O(1) if modifying in-place, O(n)O(n) with a rolling array. The code directly follows the recurrence relation. Trace through a small example by hand to see how each value is computed.

Time complexity: O(nm)O(n \cdot m).

Space complexity: O(1)O(1).