This page is still under construction.

Parts of this page are still being built. What you see may change.

The Kth Anagram in Alphabetical Order

Interview

Time limit1sMemory limit256 MB

Summary
Given a word and rank K, print the Kth distinct anagram of the word in alphabetical order.
Level

Medium5 of 10

Topics
Combinatorics, String
Solved
No attempts yet

Problem

An anagram of a string is any string you can form with exactly the same letters as the original. The original string counts as one of its own anagrams.

For example, ACM has 6 anagrams, in alphabetical order: ACM, AMC, CAM, CMA, MAC, MCA. The string ICPC has 12 anagrams, in alphabetical order: CCIP, CCPI, CICP, CIPC, CPCI, CPIC, ICCP, ICPC, IPCC, PCCI, PCIC, PICC.

Given a string and a rank KK, find the KKth anagram of that string in alphabetical order.

Input

Each line holds one query: the original word, a space, then the rank KK. A word uses uppercase letters A to Z only and has length at most 16. KK is at least 1 and at most the number of distinct anagrams of the word. The line # 0 ends the input. That line is not a query.

In the largest cases KK reaches 16!=2092278988800016! = 20922789888000, so store it in a 64-bit integer. Use long in Java or long long in C++.

Output

For each query, print the KKth anagram of the word on its own line.

Examples2

  1. Example 1

    Input
    ACM 5
    ICPC 12
    REGION 274
    # 0
    
    Expected output
    MAC
    PICC
    IGNORE
    
  2. Example 2

    Input
    A 1
    # 0
    
    Expected output
    A