Todos os desafios
Médio 0 resolvidos 0% de aceitação

Lexicographic Permutation

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

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

Exemplos

Exemplo 1
Entrada:
s = "abc"
k = 4

Saída esperada:
expected = "bca"
Entrada:
std::string s = "abc";
long long k = 4;

Saída esperada:
std::string expected = "bca";
Entrada:
string s = "abc";
long k = 4;

Saída esperada:
string expected = "bca";

Explicação

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

Exemplo 2
Entrada:
s = "312"
k = 1

Saída esperada:
expected = "123"
Entrada:
std::string s = "312";
long long k = 1;

Saída esperada:
std::string expected = "123";
Entrada:
string s = "312";
long k = 1;

Saída esperada:
string expected = "123";

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

Sort the characters first.

Dica 2

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

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

Ainda não há soluções aprovadas. Resolva e fique com o primeiro lugar.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.