Kth Smallest Instructions — LeetCode 1643 Python Solution

HardArrayMathDynamic ProgrammingCombinatorics
Problem
#1643
Reading time
3 min

The problem

Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down.

Example

Input
destination = [2,3], k = 1
Output
"HHHVV"
Explanation
All the instructions that reach (2, 3) in lexicographic order are as follows:

Python solution

Python
class Solution:
    def kthSmallestPath(self, destination: List[int], k: int) -> str:
        v, h = destination
        ans = []
        for _ in range(h + v):
            if h == 0:
                ans.append("V")
            else:
                x = comb(h + v - 1, h - 1)
                if k > x:
                    ans.append("V")
                    v -= 1
                    k -= x
                else:
                    ans.append("H")
                    h -= 1
        return "".join(ans)

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1643. Kth Smallest Instructions is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1643. Kth Smallest Instructions?
LeetCode 1643. Kth Smallest Instructions is rated Hard on LeetCode.
What topics does LeetCode 1643. Kth Smallest Instructions cover?
LeetCode 1643. Kth Smallest Instructions is tagged Array, Math, Dynamic Programming and Combinatorics on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview