Permutation Sequence
LeetCode 60 · কঠিন · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Factorial number system: index = k // fact.
আমি 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
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.
আমি কীভাবে সমাধান করেছি
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.