Tous les défis
Moyen 0 résolus 0 % de réussite

Lexicographic Permutation

Find the k-th arrangement of some distinct characters in dictionary order.

Ce que vous allez apprendre

  • Skip whole blocks of permutations at once
  • Convert a rank to a permutation
  • Work with 0-based and 1-based positions

Problème

Afficher la traduction

List every arrangement of the characters of s in dictionary order. For "abc" the list is abc, acb, bac, bca, cab, cba. Return the k-th entry, counting from 1. Generating the whole list is too slow for 12 characters (479,001,600 arrangements): each block of arrangements that starts with the same character has (length − 1)! entries, so you can pick one character at a time.

Implement lexicographic_permutation(s, k).

Input

s: Distinct characters in any order.

k: The position in the sorted list, counting from 1.

Output

Return the k-th arrangement as a string. Characters are compared by their character codes, so digits come before uppercase letters, which come before lowercase letters.

Contraintes

1 ≤ s.length ≤ 12; all characters of s are distinct; 1 ≤ k ≤ s.length!

Exemples

Exemple 1
Entrée :
s = "abc"
k = 4

Sortie attendue :
expected = "bca"
Entrée :
std::string s = "abc";
long long k = 4;

Sortie attendue :
std::string expected = "bca";
Entrée :
string s = "abc";
long k = 4;

Sortie attendue :
string expected = "bca";

Explication

The list is abc, acb, bac, bca, cab, cba, and the fourth is "bca".

Exemple 2
Entrée :
s = "312"
k = 1

Sortie attendue :
expected = "123"
Entrée :
std::string s = "312";
long long k = 1;

Sortie attendue :
std::string expected = "123";
Entrée :
string s = "312";
long k = 1;

Sortie attendue :
string expected = "123";

Explication

The first arrangement is the characters in sorted order: "123".

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Sort the characters first.

Indice 2

Each choice of first character covers (length − 1)! permutations, so dividing k − 1 by that number picks it.

Indice 3

Remove the chosen character, keep the remainder, and repeat with the rest.

Complexité attendue

O(n²) time, O(n) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.