Kth Smallest Instructions - 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.

Input & Output

Example 1 — Basic Case
$ Input: destination = [1,2], k = 1
Output: HHV
💡 Note: Need 2 horizontal moves and 1 vertical move. All valid paths sorted: ["HHV", "HVH", "VHH"]. The 1st lexicographically smallest is "HHV".
Example 2 — Middle Element
$ Input: destination = [1,2], k = 2
Output: HVH
💡 Note: All valid paths sorted: ["HHV", "HVH", "VHH"]. The 2nd lexicographically smallest is "HVH".
Example 3 — Last Element
$ Input: destination = [1,2], k = 3
Output: VHH
💡 Note: All valid paths sorted: ["HHV", "HVH", "VHH"]. The 3rd lexicographically smallest is "VHH".

Constraints

  • 1 ≤ destination[0], destination[1] ≤ 15
  • 1 ≤ k ≤ C(destination[0] + destination[1], destination[0])

Visualization

Tap to expand
Kth Smallest Instructions: Find 2nd path to (1,2)(0,0)(1,2)2H, 1VHHV (1st)HVH (2nd)VHH (3rd)All possible paths sorted lexicographicallyk=2 means we want the 2nd pathOutput: HVH
Understanding the Visualization
1
Input
destination = [1,2], k = 2 (need 2H, 1V moves)
2
Process
Use combinatorics to build path character by character
3
Output
Return the kth smallest instruction sequence
Key Takeaway
🎯 Key Insight: Use combinatorics to count paths starting with each character, allowing direct construction of the kth path without generating all possibilities
Asked in
Google 15 Amazon 12 Microsoft 8
23.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen