489. Kth Smallest Instructions
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the k-th lexicographically smallest instruction string to travel from (0, 0) to (row, column). A path consists of only 'H' (horizontal/right) and 'V' (vertical/down) moves. To reach (row, column), we must make exactly column horizontal moves and row vertical moves. The total length of any valid instruction string is row + column.
Solution
Kth Smallest Instructions in Python
import math
class Solution:
def kthSmallestPath(self, destination: List[int], k: int) -> str:
v, h = destination
result = []
for _ in range(v + h):
# If no more 'H' moves are possible, we must place 'V'
if h == 0:
result.append('V')
v -= 1
continue
# If no more 'V' moves are possible, we must place 'H'
if v == 0:
result.append('H')
h -= 1
continue
# Calculate how many permutations start with 'H'
# From the current state, we have v 'V's and h 'H's to place.
# Total remaining positions: v + h - 1
# If we place 'H', we'll have h-1 'H's left to place.
# The number of such permutations is C(v + h - 1, h - 1)
combos = math.comb(v + h - 1, h - 1)
if k <= combos:
# The kth path is in the block that starts with 'H'
result.append('H')
h -= 1
else:
# The kth path is in the block that starts with 'V'
# We skip over all the 'H' permutations
k -= combos
result.append('V')
v -= 1
return "".join(result)
Kth Smallest Instructions in Java
class Solution {
public String kthSmallestPath(int[] destination, int k) {
int v = destination[0]; // Number of vertical moves ('V')
int h = destination[1]; // Number of horizontal moves ('H')
int totalMoves = v + h;
// Precompute combinations C(n, k) using Pascal's triangle
// C[i][j] will store C(i, j)
int[][] C = new int[totalMoves + 1][totalMoves + 1];
for (int i = 0; i <= totalMoves; i++) {
C[i][0] = 1;
for (int j = 1; j <= i; j++) {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < totalMoves; i++) {
// If there are horizontal moves left to make
if (h > 0) {
// Calculate how many paths start with 'H' from this point
// Remaining moves = v + h - 1
// We need to choose h - 1 positions for 'H's
int combos = C[v + h - 1][h - 1];
if (k <= combos) {
// k is in the group of paths starting with 'H', so we must take 'H'
result.append('H');
h--;
} else {
// k is in the group of paths starting with 'V'
// Skip all combinations that start with 'H' and update k
k -= combos;
result.append('V');
v--;
}
} else {
// No horizontal moves left, must take 'V'
result.append('V');
v--;
}
}
return result.toString();
}
}
Kth Smallest Instructions in C++
class Solution {
public:
string kthSmallestPath(vector<int>& destination, int k) {
int v = destination[0]; // Number of vertical moves ('V')
int h = destination[1]; // Number of horizontal moves ('H')
int total_moves = v + h;
// Precompute combinations C(n, k)
// C[i][j] will store C(i, j)
vector<vector<int>> C(total_moves + 1, vector<int>(total_moves + 1, 0));
for (int i = 0; i <= total_moves; ++i) {
C[i][0] = 1;
for (int j = 1; j <= i; ++j) {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
string result = "";
for (int i = 0; i < total_moves; ++i) {
// If there are horizontal moves left
if (h > 0) {
// Calculate how many paths start with 'H'
// Remaining moves = v + h - 1
// We need to choose h - 1 positions for 'H's
int combos = C[v + h - 1][h - 1];
if (k <= combos) {
// k is in the 'H' group, so we must take 'H'
result += 'H';
h--;
} else {
// k is in the 'V' group, so we must take 'V'
// Skip all combinations that start with 'H'
k -= combos;
result += 'V';
v--;
}
} else {
// No horizontal moves left, must take 'V'
result += 'V';
v--;
}
}
return result;
}
};
Kth Smallest Instructions in TypeScript
function kthSmallestPath(destination: number[], k: number): string {
let v = destination[0]; // Number of vertical moves ('V')
let h = destination[1]; // Number of horizontal moves ('H')
const totalMoves = v + h;
// Precompute combinations C(n, r) using Pascal's triangle
const C: number[][] = Array(totalMoves + 1).fill(0).map(() => Array(totalMoves + 1).fill(0));
for (let i = 0; i <= totalMoves; i++) {
C[i][0] = 1;
for (let j = 1; j <= i; j++) {
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
let result = '';
for (let i = 0; i < totalMoves; i++) {
// If there are horizontal moves left
if (h > 0) {
// Calculate how many paths start with 'H' from this point
// Remaining moves = v + h - 1
// We need to choose h - 1 positions for 'H's
const combos = C[v + h - 1][h - 1];
if (k <= combos) {
// k is in the group of paths starting with 'H', so we must take 'H'
result += 'H';
h--;
} else {
// k is in the group of paths starting with 'V'
// Skip all combinations that start with 'H' and update k
k -= combos;
result += 'V';
v--;
}
} else {
// No horizontal moves left, must take 'V'
result += 'V';
v--;
}
}
return result;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.