HardNo. 1643
Kth Smallest Instructions — LeetCode 1643 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Math, Dynamic Programming, Combinatorics
- 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
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
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
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
| No. | Problem | Difficulty |
|---|---|---|
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 1735 | Count Ways to Make Array With Product | Hard |
| 1641 | Count Sorted Vowel Strings | Medium |
| 0062 | Unique Paths | Medium |
| 0313 | Super Ugly Number | Medium |
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.