1817. Kth Calm Arrangement
A florist has flower tiles, each tagged 'a', 'b' or 'c', given as the string s. A row of all the tiles is calm if no two neighbouring tiles carry the same letter. Rearrangements are counted as distinct strings, so swapping two identical tiles gives the same row.
List every distinct calm rearrangement of all the letters of s in lexicographic (alphabetical) order, and return the k-th one, counting from 1. If fewer than k calm rearrangements exist, return the empty string. You cannot list them all, since there can be billions. Instead count the completions of a partial row from the letters still left and the last letter placed, memoise those counts, and build the answer one letter at a time: for each candidate letter in order, skip its entire block of completions while k is larger than the block. Time is O(n * 13^3) at worst and space O(13^3).
Example 1
- Input:
- s = "aab", k = 1
- Output:
- "aba"
- Explanation:
Of the three rearrangements aab, aba, baa only aba has no equal neighbours, so it is the first.
Example 2
- Input:
- s = "abc", k = 4
- Output:
- "bca"
- Explanation:
All six orders are calm: abc, acb, bac, bca, cab, cba, and the fourth is bca.
Example 3
- Input:
- s = "aaab", k = 1
- Output:
- ""
- Explanation:
Three a's cannot be kept apart by one b, so no calm arrangement exists and the answer is empty.
Constraints
1 ≤ s.length ≤ 36
s consists only of 'a', 'b' and 'c'; each letter occurs at most 12 times
1 ≤ k ≤ 1015
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(13^3 * 3 + n)
- Space
- O(13^3)