|
| 1 | +/** |
| 2 | + * 1643. Kth Smallest Instructions |
| 3 | + * https://leetcode.com/problems/kth-smallest-instructions/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Bob is standing at cell (0, 0), and he wants to reach destination: (row, column). He can only |
| 7 | + * travel right and down. You are going to help Bob by providing instructions for him to reach |
| 8 | + * destination. |
| 9 | + * |
| 10 | + * The instructions are represented as a string, where each character is either: |
| 11 | + * - 'H', meaning move horizontally (go right), or |
| 12 | + * - 'V', meaning move vertically (go down). |
| 13 | + * |
| 14 | + * Multiple instructions will lead Bob to destination. For example, if destination is (2, 3), |
| 15 | + * both "HHHVV" and "HVHVH" are valid instructions. |
| 16 | + * |
| 17 | + * However, Bob is very picky. Bob has a lucky number k, and he wants the kth lexicographically |
| 18 | + * smallest instructions that will lead him to destination. k is 1-indexed. |
| 19 | + * |
| 20 | + * Given an integer array destination and an integer k, return the kth lexicographically |
| 21 | + * smallest instructions that will take Bob to destination. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} destination |
| 26 | + * @param {number} k |
| 27 | + * @return {string} |
| 28 | + */ |
| 29 | +var kthSmallestPath = function(destination, k) { |
| 30 | + let verticalMoves = destination[0]; |
| 31 | + let horizontalMoves = destination[1]; |
| 32 | + const totalMoves = verticalMoves + horizontalMoves; |
| 33 | + let path = ''; |
| 34 | + |
| 35 | + for (let i = 0; i < totalMoves; i++) { |
| 36 | + if (horizontalMoves === 0) { |
| 37 | + path += 'V'; |
| 38 | + verticalMoves--; |
| 39 | + continue; |
| 40 | + } |
| 41 | + const combinations = calculateCombinations( |
| 42 | + verticalMoves + horizontalMoves - 1, |
| 43 | + horizontalMoves - 1 |
| 44 | + ); |
| 45 | + if (k <= combinations) { |
| 46 | + path += 'H'; |
| 47 | + horizontalMoves--; |
| 48 | + } else { |
| 49 | + path += 'V'; |
| 50 | + verticalMoves--; |
| 51 | + k -= combinations; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return path; |
| 56 | +}; |
| 57 | + |
| 58 | +function calculateCombinations(n, r) { |
| 59 | + if (r < 0 || r > n) return 0; |
| 60 | + let result = 1; |
| 61 | + for (let i = 1; i <= r; i++) { |
| 62 | + result = result * (n - i + 1) / i; |
| 63 | + } |
| 64 | + return Math.floor(result); |
| 65 | +} |
0 commit comments