The Kth Anagram in Alphabetical Order
InterviewTime limit1sMemory limit256 MB
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 , find the th anagram of that string in alphabetical order.
Input
Each line holds one query: the original word, a space, then the rank . A word uses uppercase letters A to Z only and has length at most 16. 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 reaches , so store it in a 64-bit integer. Use long in Java or long long in C++.
Output
For each query, print the th anagram of the word on its own line.