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.