LeetCode 1643: Kth Smallest Instructions
Problem Description
Explanation:
To solve this problem, we can use a combinatorial approach known as "Binomial Coefficient" to determine the number of ways to reach the destination cell. Then, we can construct the kth lexicographically smallest instruction by simulating Bob's movements based on whether the next move should be horizontal or vertical.
- Calculate the number of ways to reach the destination cell using the formula nCr(row + column, row).
- Determine whether the kth lexicographically smallest instruction falls in the range of ways to move horizontally or vertically from the current position.
- Recursively construct the kth lexicographically smallest instruction by choosing the correct move based on the remaining number of ways to move horizontally or vertically.
Time Complexity: O(row + column)
Space Complexity: O(row + column)
:
Solutions
class Solution {
public String kthSmallestPath(int[] destination, int k) {
int row = destination[0];
int col = destination[1];
int totalMoves = row + col;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < totalMoves; i++) {
int hMoves = totalMoves - i - 1;
int waysToMoveHorizontally = hMoves >= row ? nCr(hMoves, row) : 0;
if (waysToMoveHorizontally >= k) {
sb.append('H');
row--;
} else {
sb.append('V');
k -= waysToMoveHorizontally;
col--;
}
}
return sb.toString();
}
private int nCr(int n, int r) {
long res = 1;
for (int i = 0; i < r; i++) {
res = res * (n - i) / (i + 1);
}
return (int) res;
}
}
Loading editor...