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 of i from 1 to s.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
k-th Lexicographical Happy String INPUT Happy String Rules: • Uses only: 'a', 'b', 'c' • No adjacent same chars • s[i] != s[i+1] All Happy Strings (n=1): "a" k=1 "b" k=2 "c" k=3 Input Values: n = 1 (length) k = 3 (position) Lexicographical: a < b < c Total count: 3 strings ALGORITHM STEPS 1 Count Total Strings Total = 3 × 2^(n-1) 3 × 2^0 = 3 strings 2 Check k Valid k <= total? 3 <= 3 [OK] 3 Calculate First Char Each char covers 2^(n-1) = 1 Char Range k=3? 'a' k=1 no 'b' k=2 no 'c' k=3 [OK] 4 Build Result n=1: Only first char needed result="c" FINAL RESULT The 3rd Happy String: "c" Verification: All strings sorted: 1. "a" 2. "b" 3. "c" <-- k=3 [OK] Output: "c" Key Insight: Mathematical k-th calculation avoids generating all strings. For length n, there are 3×2^(n-1) happy strings. The first character divides strings into 3 groups of 2^(n-1). We calculate which group k falls into, then recursively find subsequent characters. Time: O(n), Space: O(n) -- much better than generating all O(3×2^(n-1)) strings! TutorialsPoint - The k-th Lexicographical String of All Happy Strings of Length n | Mathematical k-th Calculation
Asked in
Facebook 3 Google 2
23.5K Views
Medium Frequency
~25 min Avg. Time
892 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