Kth Smallest Instructions solution and explanation
9 more videos on this problem
Leetcode 1643. Kth Smallest InstructionsFraz · 11:20 · 7K views
LeetCode 1643. Kth Smallest InstructionsHappy Coding · 19:24 · 1K views
1643. Kth Smallest Instructions (Leetcode Hard)Programming Live with Larry · 44:14 · 543 views
【每日一题】1643. Kth Smallest Instructions, 11/5/2020Huifeng Guan · 16:21 · 470 views
3min to learn leetcode 1643. Kth Smallest Instructionst q · 1:58 · 438 views
LeetCode #1643 | Hard | Kth Smallest Instructions | PythonAndy Tu · 14:14 · 364 views
Leetcode 1643. Kth Smallest InstructionsFearless Learner · 9:55 · 142 views
ข้อ 1643. Kth Smallest Instructions | LeetCodeThakorn Jareonrat · 13:58 · 5 views
Code Review: LeetCode - Weekly Contest 213 - Kth Smallest InstructionsRoel Van de Paar · 3:06 · 3 views
LeetCode 1643: Kth Smallest InstructionsAlitaCode · 30:29 · 2 views
The problem
Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only travel right and down. You are going to help Bob by providing instructions for him to reach destination.
The instructions are represented as a string, where each character is either:
'H', meaning move horizontally (go right), or'V', meaning move vertically (go down).
Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), both "HHHVV" and "HVHVH" are valid instructions.
However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically smallest instructions that will lead him to destination. k is 1-indexed.
Given an integer array destination and an integer k, return the kth lexicographically smallest instructions that will take Bob to destination.
Example 1:

Input: destination = [2,3], k = 1 Output: "HHHVV" Explanation: All the instructions that reach (2, 3) in lexicographic order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH", "HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].
Example 2:
Input: destination = [2,3], k = 2 Output: "HHVHV"
Example 3:
Input: destination = [2,3], k = 3 Output: "HHVVH"
Constraints:
destination.length == 21 <= row, column <= 151 <= k <= nCr(row + column, row), wherenCr(a, b)denotesachooseb.
Approach overview
Problem Overview: You are given a grid destination [row, col]. Starting from (0,0), you must reach the destination using only H (right) and V (down) moves. Among all valid instruction strings, return the k-th smallest in lexicographic order. The total length of the string is row + col, containing exactly row V's and col H's.
Approach 1: Dynamic Programming Counting (O(row * col) time, O(row * col) space)
The key observation: instead of generating all paths, count how many paths start with a particular move. Use dynamic programming to compute the number of ways to reach the destination from every cell. Let dp[r][c] represent the number of valid paths from that position to the destination. The recurrence is straightforward: dp[r][c] = dp[r+1][c] + dp[r][c+1]. When constructing the answer, try placing H first because it is lexicographically smaller. If the number of paths starting with H is at least k, append H. Otherwise append V and subtract that count from k. Continue until all moves are placed. This approach explicitly models the grid and is easy to reason about using dynamic programming.
Approach 2: Combinatorial Greedy (O((row + col)^2) time, O((row + col)^2) space)
A more mathematical view treats the path as arranging characters. Any valid path is a permutation of row V's and col H's. The number of paths starting with H equals the number of ways to arrange the remaining characters: C(row + col - 1, col - 1). Compute binomial coefficients using Pascal's triangle or a combination table. At each step, check how many sequences start with H. If k is less than or equal to that count, append H. Otherwise append V and reduce k by that count. Decrease the remaining counts and repeat. This approach avoids storing a grid and relies on combinatorics and greedy decision making.
The algorithm effectively performs lexicographic ranking of sequences with fixed character counts. Each decision narrows the search space by skipping entire groups of sequences using combinatorial counts rather than enumeration.
Recommended for interviews: The combinatorial greedy approach is the expected solution. It shows that you recognize the path count as a binomial coefficient and can construct the k-th sequence directly. Explaining the DP counting version first can help demonstrate understanding, but interviewers usually want the optimized reasoning using math and combinations.
Approach 1: Combinatorial Approach
To solve the problem, we consider the possible paths to the destination using combinatorial logic. The objective in this approach is to determine if a 'H' or 'V' should be appended next based on how many sequences remain. We use combinations to count these sequences instead of generating them explicitly. The binomial coefficient helps decide if the next letter should be an 'H' or a 'V', and thereby decide the kth path without having to construct all possible paths:
from math import comb
def kthSmallestPath(destination, k):
row, column = destination
path = []
for _ in range(row + column):
if column > 0: # Consider an 'H'
count = comb(row + column - 1, row)
if k > count:
path.append('V')
k -= count
row -= 1
else:
path.append('H')
column -= 1
else: # Only 'V' can be appended
path.append('V')
row -= 1
return ''.join(path)
# Example Usage
print(kthSmallestPath([2, 3], 1))#include <iostream>
#include <vector>
#include <string>
using namespace std;
int binomialCoeff(int n, int k) {
if (k > n) return 0;
if (k == 0 || k == n) return 1;
int res = 1;
for (int i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
string kthSmallestPath(vector<int>& destination, int k) {
int row = destination[0], column = destination[1];
string result;
for (int step = 0; step < row + column; ++step) {
if (column > 0) {
int count = binomialCoeff(row + column - 1, column - 1);
if (k > count) {
result += 'V';
k -= count;
--row;
} else {
result += 'H';
--column;
}
} else {
result += 'V';
--row;
}
}
return result;
}
int main() {
vector<int> destination = {2, 3};
int k = 1;
cout << kthSmallestPath(destination, k) << endl;
return 0;
}This Python solution uses the combinatorial library to calculate the number of ways remaining to complete a path. Initially, it attempts to append an 'H'. If the number of ways exceeds k, it appends 'H'; otherwise, it appends 'V'. This decision process is repeated until the destination is reached.
Time Complexity: O(n + m), where n is the number of rows and m is the number of columns. Each step either appends 'H' or 'V'.
Space Complexity: O(n + m) for storing the path string.
Approach 2: Dynamic Programming Approach
The dynamic programming approach involves creating a 2D table that keeps track of the number of ways paths can be constructed to reach certain coordinates. This table helps us quickly decide if the nth or kth smallest lexicographic sequence favors a horizontal or vertical move:
import java.util.Arrays;
public class KthSmallestInstructions {
public String kthSmallestPath(int[] destination, int k) {
int row = destination[0], column = destination[1];
StringBuilder result = new StringBuilder();
int[][] dp = new int[row + 1][column + 1];
for (int r = 0; r <= row; ++r) dp[r][0] = 1;
for (int c = 0; c <= column; ++c) dp[0][c] = 1;
for (int r = 1; r <= row; r++) {
for (int c = 1; c <= column; c++) {
dp[r][c] = dp[r-1][c] + dp[r][c-1];
}
}
for (int step = 0; step < row + column; ++step) {
if (column > 0) {
if (k <= dp[row][column - 1]) {
result.append('H');
column -= 1;
} else {
result.append('V');
k -= dp[row][column - 1];
row -= 1;
}
} else {
result.append('V');
row -= 1;
}
}
return result.toString();
}
public static void main(String[] args) {
KthSmallestInstructions solution = new KthSmallestInstructions();
System.out.println(solution.kthSmallestPath(new int[]{2, 3}, 1));
}
}function kthSmallestPath(destination, k) {
const [row, column] = destination;
let dp = Array.from({ length: row + 1 }, () => Array(column + 1).fill(0));
for (let r = 0; r <= row; ++r) dp[r][0] = 1;
for (let c = 0; c <= column; ++c) dp[0][c] = 1;
for (let r = 1; r <= row; ++r) {
for (let c = 1; c <= column; ++c) {
dp[r][c] = dp[r - 1][c] + dp[r][c - 1];
}
}
let res = '';
let r = row, c = column;
while (r > 0 && c > 0) {
if (k <= dp[r][c - 1]) {
res += 'H';
c -= 1;
} else {
res += 'V';
k -= dp[r][c - 1];
r -= 1;
}
}
while (c-- > 0) res += 'H';
while (r-- > 0) res += 'V';
return res;
}
console.log(kthSmallestPath([2, 3], 1));This Java solution precomputes the number of ways to reach each coordinate using a dynamic programming table. It efficiently decides the next move by checking the number of ways remaining in a coordinated direction. This ensures correct lexicographic path selection according to k.
Time Complexity: O(n * m), where n is the number of rows and m is the number of columns. This is due to filling the DP table.
Space Complexity: O(n * m), for the DP table storage.
Approach 3: Default Approach
func kthSmallestPath(destination []int, k int) string {
v, h := destination[0], destination[1]
n := v + h
c := make([][]int, n+1)
for i := range c {
c[i] = make([]int, h+1)
c[i][0] = 1
}
for i := 1; i <= n; i++ {
for j := 1; j <= h; j++ {
c[i][j] = c[i-1][j] + c[i-1][j-1]
}
}
ans := []byte{}
for i := 0; i < n; i++ {
if h == 0 {
ans = append(ans, 'V')
} else {
x := c[v+h-1][h-1]
if k > x {
ans = append(ans, 'V')
k -= x
v--
} else {
ans = append(ans, 'H')
h--
}
}
}
return string(ans)
}Complexity comparison
| Approach | Complexity |
|---|---|
| Combinatorial Approach | Time Complexity: O(n + m), where n is the number of rows and m is the number of columns. Each step either appends 'H' or 'V'. Space Complexity: O(n + m) for storing the path string. |
| Dynamic Programming Approach | Time Complexity: O(n * m), where n is the number of rows and m is the number of columns. This is due to filling the DP table. Space Complexity: O(n * m), for the DP table storage. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming Counting | O(row * col) | O(row * col) | When you want a clear grid-based interpretation and straightforward implementation |
| Combinatorial Greedy | O((row + col)^2) | O((row + col)^2) | Preferred solution for interviews; directly computes lexicographic order using combinations |
Frequently asked questions
Is Kth Smallest Instructions easy or hard?
The problem is rated Hard on LeetCode because it requires recognizing the combinatorial structure of the paths and using lexicographic ranking logic. Once the binomial counting insight is clear, the implementation becomes relatively straightforward.
Kth Smallest Instructions Python/Java solution
Python and Java implementations typically precompute combination values using a 2D array. Then a greedy loop builds the result string by comparing k with the number of sequences that begin with 'H'. The same logic works in C++, JavaScript, and other languages.
How to solve Kth Smallest Instructions in O(n)?
After precomputing combination values, building the instruction string is O(n) where n = row + col. At each step you check C(remainingMoves-1, remainingH-1) to decide whether the next character should be 'H' or 'V'. This greedy selection skips large groups of sequences at once.
What is the best approach for Kth Smallest Instructions?
The combinatorial greedy approach is the most efficient and commonly expected solution. At each step you count how many paths start with 'H' using the binomial coefficient C(row+col-1, col-1). If k is within that range, choose 'H'; otherwise choose 'V' and subtract the skipped count. This constructs the k-th lexicographic sequence without generating all paths.
Is Kth Smallest Instructions asked at Google/Amazon/Meta?
Problems involving combinatorics and lexicographic ordering frequently appear in interviews at companies like Google, Amazon, and Meta. Variants include k-th permutation, k-th lexicographic path, or counting grid paths with constraints.
What data structure is used in Kth Smallest Instructions?
The solution primarily relies on combinatorics and counting rather than complex data structures. Most implementations use a 2D array for Pascal's triangle or a DP table to store binomial coefficients and path counts.
What is the time complexity of Kth Smallest Instructions?
The typical solution precomputes binomial coefficients using Pascal's triangle in O((row+col)^2) time and space. Constructing the final instruction string then takes O(row+col). Overall complexity is dominated by the combination preprocessing step.
