The k-th Lexicographical String of All Happy Strings of Length n - Problem
A happy string is a delightful sequence of characters that follows two simple rules:
- It contains only the letters
'a','b', and'c' - No two adjacent characters are the same (no consecutive duplicates!)
Examples of happy strings: "abc", "ac", "b", "abcbabcbcb"
Examples of sad strings: "aa", "baa", "ababbc"
Your Mission: Given two integers n (length) and k (position), imagine generating ALL possible happy strings of length n and sorting them in lexicographical (dictionary) order. Your task is to return the k-th string from this sorted list.
If there are fewer than k happy strings of length n, return an empty string "".
Goal: Find the k-th lexicographically smallest happy string of length n without generating all possible strings.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 1, k = 3
โบ
Output:
"c"
๐ก Note:
Happy strings of length 1: ["a", "b", "c"]. The 3rd string is "c".
example_2.py โ Multiple Characters
$
Input:
n = 1, k = 4
โบ
Output:
""
๐ก Note:
There are only 3 happy strings of length 1, so k=4 exceeds the count. Return empty string.
example_3.py โ Length 3 String
$
Input:
n = 3, k = 9
โบ
Output:
"cab"
๐ก Note:
All happy strings of length 3 sorted: ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. The 9th string is "cab".
Constraints
- 1 โค n โค 10
- 1 โค k โค 500
- Happy strings use only characters 'a', 'b', 'c'
- No two adjacent characters can be the same
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Tree Size
For length n: 3 choices for first char ร 2 choices for each remaining = 3ร2^(n-1) total strings
2
Navigate by Subtree Counts
At each level, determine which character's subtree contains the k-th string
3
Direct Construction
Build the string character by character using mathematical calculation
4
Early Termination
If k exceeds total possible strings, return empty string immediately
Key Takeaway
๐ฏ Key Insight: By calculating subtree sizes mathematically, we can jump directly to the k-th string without generating all possibilities, making this an elegant O(n) solution.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code