Tutte le sfide
Media 0 risolte 0% di accettazione

Lexicographic Permutation

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
s = "abc"
k = 4

Output atteso:
expected = "bca"
Input:
std::string s = "abc";
long long k = 4;

Output atteso:
std::string expected = "bca";
Input:
string s = "abc";
long k = 4;

Output atteso:
string expected = "bca";

Spiegazione

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

Esempio 2
Input:
s = "312"
k = 1

Output atteso:
expected = "123"
Input:
std::string s = "312";
long long k = 1;

Output atteso:
std::string expected = "123";
Input:
string s = "312";
long k = 1;

Output atteso:
string expected = "123";

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Sort the characters first.

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.