Kth Smallest Instructions — LeetCode 1643 Python Solution
HardArrayMathDynamic ProgrammingCombinatorics
- Problem
- #1643
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(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
LeetCode 1467Probability of a Two Boxes Having The Same Number of Distinct BallsHardLeetCode 1569Number of Ways to Reorder Array to Get Same BSTHardLeetCode 1735Count Ways to Make Array With ProductHardLeetCode 1641Count Sorted Vowel StringsMediumLeetCode 62Unique PathsMediumLeetCode 313Super Ugly NumberMedium
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.