Problem Description
Given a destination specified by (row, column) and knowing that Bob starts at (0, 0) and can only move right (represented by 'H') and down (represented by 'V'), return the kth lexicographically smallest valid instruction string (1-indexed) that leads Bob to the destination. Lexicographic order follows that 'H' is considered smaller than 'V' (i.e. “HHHVV” comes before “HHVHV”).
Key Insights
- The task is equivalent to selecting positions for 'H' moves among a total of (row + column) moves.
- The number of valid instruction strings is given by the combination C(totalMoves, countH).
- Use combinatorics to decide each character: if placing 'H' first yields a sufficient number of sequences to cover kth smallest, then the first character is 'H', otherwise it is 'V' and we update k accordingly.
- Precompute binomial coefficients (or compute on the fly) for combinations to avoid repetitive calculations since moves are at most around 30.
- The solution builds the instruction string one character at a time based on remaining counts of H's and V's.
Space and Time Complexity
Time Complexity: O((row + column)^2) due to the combination calculations for each position. Space Complexity: O(row + column) for the output string; additional space for combination table is O((row + column)^2), which is acceptable with given constraints.
Solution
We maintain two counters: one for the number of horizontal moves (H) and one for vertical moves (V). For each move in the resulting string, we decide if the current position should be an 'H' or a 'V' by checking the count of sequences that would start with 'H'. This count is computed by the binomial coefficient C(remainingMoves-1, remainingH-1) (if we choose 'H'). If k is less than or equal to this count, we pick 'H'; otherwise, we pick 'V' and subtract this count from k. We repeat this process until the instruction string is complete.
We use a helper function to compute the binomial coefficient (combinations) either recursively or with a precomputed table.