#1643
Kth Smallest Instructions
HardArrayMathDynamic ProgrammingCombinatoricsDynamic ProgrammingCombinatorics
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n!) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating all combinations, we can use combinatorial counting to directly find the k-th instruction. This approach is efficient and avoids unnecessary computations.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty result string and set the remaining row and column moves.
- 2Step 2: For each step, calculate how many valid sequences start with 'H' and 'V'.
- 3Step 3: If the number of sequences starting with 'H' is greater than or equal to k, append 'H' to the result; otherwise, append 'V' and adjust k accordingly.
- 4Step 4: Repeat until all moves are used.
solution.py19 lines
1# Full working Python code
2from math import comb
3
4def kthSmallestInstructions(destination, k):
5 row, column = destination
6 result = []
7 while row > 0 or column > 0:
8 if column > 0:
9 count_H = comb(row + column - 1, row)
10 else:
11 count_H = 0
12 if k <= count_H:
13 result.append('H')
14 column -= 1
15 else:
16 result.append('V')
17 k -= count_H
18 row -= 1
19 return ''.join(result)ℹ
Complexity note: The time complexity is O(n) since we only iterate through the moves, and the space complexity is O(1) as we use a constant amount of space.
- 1Understanding combinatorial counting can greatly reduce the complexity of problems involving sequences.
- 2Recognizing patterns in the problem (like the number of valid sequences) helps in making efficient decisions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.