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.