K-th Beautiful String

You are given two integers n and k.

Consider all possible strings of length n that consist of exactly two 'b' characters and n - 2 'a' characters. Imagine all of these valid strings are generated and sorted in strict lexicographical (alphabetical) order.

Your task is to find and return the kth string from this sorted list. (Assume 1-based indexing).

Example 1:

Input: n = 5, k = 1

Output: "aaabb"

Explanation:

The very first string in alphabetical order groups all 'a's at the beginning and the two 'b's at the end.

Example 2:

Input: n = 5, k = 2

Output: "aabab"

Explanation:

The second string shifts the leftmost 'b' one position to the left compared to the first string.

Now Your Turn!

Pick the correct output for the given input

Input: n = 3, k = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 3 <= n <= 105
  • 1 <= k <= min(2*109, n*(n - 1) / 2)

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
string kthBeautifulString(int n, int k) {
}
};
Test Case

Input:

K
N