Tensorum
YouTubeसीखना शुरू करें
LeetCode 60 · Permutations

Permutation Sequence

LeetCode 60 · कठिन · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Factorial number system: index = k // fact.

कठिनMathRecursion

मैंने Permutation Sequence (LeetCode 60) ऐसे हल किया — Permutations पैटर्न का एक कठिन प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Permutations of n numbers come in blocks of (n−1)! that share the same first number. So (k−1) // (n−1)! tells you which number comes first; recurse on the remainder with one fewer number.

Approach

  1. 1

    fact = (n−1)!, k = k − 1 (0-based).

  2. 2

    Pick nums[k // fact], remove it, k %= fact.

  3. 3

    Shrink fact by the number of remaining values; repeat.

मैंने कैसे हल किया

Factorial indexingPythonO(n²) time
class Solution:
    def getPermutation(self, n: int, k: int) -> str:
         #1,2,3,4 - 24 permutations
        #we need to find 16th permutation
        """
        0 - 1 - 2,3,4 - range(0-5) - permutation of 2,3,4 -> fact 6
        1 - 2 - 1,3,4  - range(6-11) - permutation of 1,3,4 -> fact 6
        2 - 3 - 1,2,4 - range(12-17) - permutation of 1,2,4 -> fact 6
        3 - 4 - 1,2,3  - range(17-23) - permutation of 1,2,3 ->fact 6

        1,2,3,4
        0,1,2,3

        16//6 - 2nd row corresponds to 3, put 3,_,_,_
        After going to 2nd row, we need to find 16%6 = 4 th permutation

        0 - 1 - 2,3 - range(0-1) - permuation of 2,3 - fact 2
        1 - 2 - 1,3 - range(2-3) - permuation of 1,3 - fact 2
        2 - 4 - 1,2 - range(4-5)- permuation of 1,2 - fact 2

        k = 4, fact 2

        4//2 - 2nd row corresponds to 4 - 3,4,_,_
        4%2 - 0 - 0 th permuation 
    
        """
        fact = 1
        nums = [i+1 for i in range(n)]
        for i in range(1,n):
            fact = fact*i
        k=k-1
        res=""
        while n>0:
            index = k//fact
            res+=str(nums[index])
            nums.pop(index)
            k=k%fact
            if not nums:
                break
            fact = fact//len(nums)
        return res

स्टेप-थ्रू लोड हो रहा है…

Permutation Sequence — अक्सर पूछे जाने वाले प्रश्न

Permutation Sequence के पीछे intuition क्या है?

Permutations of n numbers come in blocks of (n−1)! that share the same first number. So (k−1) // (n−1)! tells you which number comes first; recurse on the remainder with one fewer number.

Permutation Sequence (LeetCode 60) कैसे हल करें?

1. fact = (n−1)!, k = k − 1 (0-based). 2. Pick nums[k // fact], remove it, k %= fact. 3. Shrink fact by the number of remaining values; repeat.

Permutation Sequence की time और space complexity क्या है?

Time: O(n²)। Space: O(n)। (Accepted approach: Factorial indexing।)

Permutation Sequence में आम गलतियाँ क्या हैं?

Convert k to 0-based first.