|
| 1 | +# K-th Smallest Lexicographical Path |
| 2 | + |
| 3 | +## Problem Description |
| 4 | + |
| 5 | +You are given a grid with dimensions defined by a destination point `[row, column]`. Starting at the origin `(0, 0)`, you can only move **right ('H')** or **down ('V')**. Your task is to find the **k-th lexicographically smallest path** that leads to the destination. |
| 6 | + |
| 7 | +## Example |
| 8 | + |
| 9 | +Input: |
| 10 | +```c |
| 11 | +destination = [2, 3] // 2 vertical moves, 3 horizontal moves |
| 12 | +k = 4 |
| 13 | +``` |
| 14 | + |
| 15 | +Output: |
| 16 | +``` |
| 17 | +"HVHHV" |
| 18 | +``` |
| 19 | + |
| 20 | +## Total Number of Paths |
| 21 | + |
| 22 | +To reach a point `(v, h)`, where: |
| 23 | +- `v` is the number of vertical steps (`V`), |
| 24 | +- `h` is the number of horizontal steps (`H`), |
| 25 | + |
| 26 | +you need to construct a string of length `v + h` that consists of exactly: |
| 27 | +- `v` occurrences of `'V'`, |
| 28 | +- `h` occurrences of `'H'`. |
| 29 | + |
| 30 | +The total number of such unique paths is given by the combination formula: |
| 31 | + |
| 32 | +\[ |
| 33 | +C(v + h, h) = \frac{(v + h)!}{v! \cdot h!} |
| 34 | +\] |
| 35 | + |
| 36 | +This represents the number of ways to arrange `h` H's among `v + h` total steps. |
| 37 | + |
| 38 | +--- |
| 39 | + |
| 40 | +## Approach: Combinatorial Logic |
| 41 | + |
| 42 | +We want to construct the k-th lexicographical string, step by step. At every step, we decide whether to place an `'H'` or a `'V'` next. |
| 43 | + |
| 44 | +### Lexicographical Order |
| 45 | + |
| 46 | +- `'H'` comes before `'V'` in lexicographical order. |
| 47 | +- So, in order to build the smallest string, we prefer `'H'` whenever possible. |
| 48 | + |
| 49 | +### Recursive Logic |
| 50 | + |
| 51 | +At each position in the result string: |
| 52 | +1. We try placing `'H'`. |
| 53 | + - If we do this, the remaining number of valid paths is `C(v + h - 1, h - 1)`. |
| 54 | + - If `k` is **less than or equal to** this value, then we know the desired path starts with `'H'`. |
| 55 | +2. Otherwise, we place `'V'`, reduce `k` accordingly (since we skipped over the paths that started with `'H'`), and continue. |
| 56 | + |
| 57 | +This process repeats until all steps are placed. |
| 58 | + |
| 59 | +--- |
0 commit comments