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
STARTabc2^(n-1) strings2^(n-1) strings2^(n-1) strings๐Ÿงฎ Mathematical Magic:โ€ข Position 1: k รท 2^(n-1) tells us which character (a=0, b=1, c=2)โ€ข Position i: Available chars = {a,b,c} - {previous_char}โ€ข Each position: char_index = k รท 2^(remaining_positions)โ€ข Update: k = k % 2^(remaining_positions)โœ“Direct Navigation: O(n) Time, O(1) Space
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.
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 20
28.8K Views
Medium-High Frequency
~18 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen