The k-th Lexicographical String of All Happy Strings of Length n - Problem
A happy string is a string that:
- consists only of letters of the set
['a', 'b', 'c']. s[i] != s[i + 1]for all values ofifrom1tos.length - 1(string is 1-indexed).
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order.
Return the k-th string of this list or return an empty string if there are less than k happy strings of length n.
Input & Output
Example 1 — Basic Case
$
Input:
n = 1, k = 3
›
Output:
c
💡 Note:
For n=1, happy strings are: ['a', 'b', 'c']. The 3rd string is 'c'.
Example 2 — Two Characters
$
Input:
n = 2, k = 3
›
Output:
ba
💡 Note:
For n=2, happy strings are: ['ab', 'ac', 'ba', 'bc', 'ca', 'cb']. The 3rd string is 'ba'.
Example 3 — k Too Large
$
Input:
n = 2, k = 7
›
Output:
💡 Note:
There are only 6 happy strings of length 2, so k=7 exceeds the count. Return empty string.
Constraints
- 1 ≤ n ≤ 4
- 1 ≤ k ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
n=2, k=3 (find 3rd happy string of length 2)
2
Happy Strings
Generate: ab, ac, ba, bc, ca, cb (6 total)
3
Output
Return 3rd string: "ba"
Key Takeaway
🎯 Key Insight: Happy strings have exactly 3 × 2^(n-1) possibilities, allowing direct mathematical calculation
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code