We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def nth_lexicographic_permutation(n, word):
n -= 1 # Adjusting for 0-based indexing
factorials = [factorial(i) for i in range(len(word))]
result = ""
available = list(word)
for i in range(len(word), 0, -1):
index = n // factorials[i-1]
n = n % factorials[i-1]
result += available.pop(index)
return result
word = "abcdefghijklm"
for _ in range(int(input().strip())
n = int(input().strip())
result = nth_lexicographic_permutation(n, word)
print(result)
index = n // factorials[i-1]
n = n % factorials[i-1]
result += available.pop(index)
return result
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #24: Lexicographic permutations
You are viewing a single comment's thread. Return to all comments →
in python3
def factorial(n): result = 1 for i in range(1, n+1): result *= i return result
def nth_lexicographic_permutation(n, word): n -= 1 # Adjusting for 0-based indexing factorials = [factorial(i) for i in range(len(word))] result = "" available = list(word) for i in range(len(word), 0, -1): index = n // factorials[i-1] n = n % factorials[i-1] result += available.pop(index) return result
word = "abcdefghijklm" for _ in range(int(input().strip()) n = int(input().strip()) result = nth_lexicographic_permutation(n, word) print(result)