LeetCode 1643: Kth Smallest Instructions Solution

Master LeetCode problem 1643 (Kth Smallest Instructions), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1643. Kth Smallest Instructions

Problem Explanation

Explanation:

To solve this problem, we can use a combinatorial approach known as "Binomial Coefficient" to determine the number of ways to reach the destination cell. Then, we can construct the kth lexicographically smallest instruction by simulating Bob's movements based on whether the next move should be horizontal or vertical.

  1. Calculate the number of ways to reach the destination cell using the formula nCr(row + column, row).
  2. Determine whether the kth lexicographically smallest instruction falls in the range of ways to move horizontally or vertically from the current position.
  3. Recursively construct the kth lexicographically smallest instruction by choosing the correct move based on the remaining number of ways to move horizontally or vertically.

Time Complexity: O(row + column)
Space Complexity: O(row + column)

:

Solution Code

class Solution {
    public String kthSmallestPath(int[] destination, int k) {
        int row = destination[0];
        int col = destination[1];
        int totalMoves = row + col;
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < totalMoves; i++) {
            int hMoves = totalMoves - i - 1;
            int waysToMoveHorizontally = hMoves >= row ? nCr(hMoves, row) : 0;
            
            if (waysToMoveHorizontally >= k) {
                sb.append('H');
                row--;
            } else {
                sb.append('V');
                k -= waysToMoveHorizontally;
                col--;
            }
        }
        
        return sb.toString();
    }
    
    private int nCr(int n, int r) {
        long res = 1;
        for (int i = 0; i < r; i++) {
            res = res * (n - i) / (i + 1);
        }
        return (int) res;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1643 (Kth Smallest Instructions)?

This page provides optimized solutions for LeetCode problem 1643 (Kth Smallest Instructions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1643 (Kth Smallest Instructions)?

The time complexity for LeetCode 1643 (Kth Smallest Instructions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1643 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1643 in Java, C++, or Python.

Back to LeetCode Solutions