The k-th Lexicographical String of All Happy Strings of Length n (LeetCode 1415): Solution and Explanation
Happy strings use only a, b and c with no two equal neighbours. List those of length n in sorted order and return the k-th, or an empty string if the list is shorter.
Intuition
The direct approach is backtracking: build strings letter by letter in a, b, c order, skip a letter equal to the previous one, and stop at the k-th complete string. That works, but it walks past k - 1 strings first.
Count instead. The first letter has 3 choices and each later letter has 2, so there are 3 x 2^(n-1) happy strings. Fixing a prefix of length i leaves 2^(n-i) ways to finish it.
In sorted order, all strings with the same prefix sit next to each other. So the list is cut into 3 equal blocks by the first letter, each of those into 2 equal blocks by the second letter, and so on.
Finding the k-th string is then like reading the digits of k - 1: divide by the block size to pick the block, keep the remainder as the offset inside it, halve the block size and repeat.
Approach: Pick a block at every level
- Set
block = 2^(n-1). Ifk > 3 * block, return the empty string. - Make
kzero-based withk -= 1. The first letter is"abc"[k // block]. - While
block > 1: setk %= block(the offset inside the chosen block) and halveblock. - The next letter is one of the two letters different from the last one, in alphabetical order. Pick index
k // block. - Return the letters joined together.
Step-by-step example
n = 3, k = 9
- There are 3 x 2^2 = 12 happy strings of length 3. Since 9 <= 12, the answer exists.
- k - 1 = 8 and block = 4. 8 // 4 = 2, so the string is in the third block: it starts with 'c'.
- Offset 8 % 4 = 0, block = 2. After 'c' the options are 'a' and 'b'. 0 // 2 = 0 picks 'a': prefix "ca".
- Offset 0 % 2 = 0, block = 1. After 'a' the options are 'b' and 'c'. 0 // 1 = 0 picks 'b': prefix "cab".
- The block size is 1, so the string is complete. Return "cab".
Code: Python, Java, C++
1class Solution:
2 def getHappyString(self, n: int, k: int) -> str:
3 block = 1 << (n - 1)
4 if k > 3 * block:
5 return ""
6 k -= 1
7 result = ["abc"[k // block]]
8 while block > 1:
9 k %= block
10 block //= 2
11 options = [ch for ch in "abc" if ch != result[-1]]
12 result.append(options[k // block])
13 return "".join(result)1class Solution {
2 public String getHappyString(int n, int k) {
3 int block = 1 << (n - 1);
4 if (k > 3 * block) {
5 return "";
6 }
7 k--;
8 StringBuilder result = new StringBuilder();
9 result.append((char) ('a' + k / block));
10 while (block > 1) {
11 k %= block;
12 block /= 2;
13 char last = result.charAt(result.length() - 1);
14 String options = last == 'a' ? "bc" : last == 'b' ? "ac" : "ab";
15 result.append(options.charAt(k / block));
16 }
17 return result.toString();
18 }
19}1class Solution {
2public:
3 string getHappyString(int n, int k) {
4 int block = 1 << (n - 1);
5 if (k > 3 * block) {
6 return "";
7 }
8 k--;
9 string result(1, (char) ('a' + k / block));
10 while (block > 1) {
11 k %= block;
12 block /= 2;
13 char last = result.back();
14 string options = last == 'a' ? "bc" : last == 'b' ? "ac" : "ab";
15 result += options[k / block];
16 }
17 return result;
18 }
19};Time and space complexity
O(n)
One division and one remainder per letter, and there are n letters.
O(n)
Only the answer string is stored.
Other approaches
Backtracking with a counter (time O(k * n), space O(n))
Generate happy strings in lexicographical order with DFS, trying a, b, c and skipping the previous letter. Count complete strings and stop at the k-th one. Simple, and fast enough because k is at most 100.
Generate all and index (time O(3 * 2^n * n), space O(3 * 2^n * n))
Build every happy string of length n into a list, then return element k - 1 if it exists. It is the easiest to write but stores up to 1536 strings for n = 10.
Common mistakes
- Forgetting that k is 1-indexed. Subtract 1 before dividing, or the block choice is off by one at the boundaries.
- Using 3 options at every level. Only the first letter has 3 choices; every later letter has 2.
- Not checking
k > 3 * 2^(n-1)first. Without it the first division picks an index past 'c'. - Ordering the two options wrong. They must stay in alphabetical order so that block 0 holds the smaller strings.
Frequently asked questions
Why does dividing k - 1 by the block size pick the right letter?
Strings with the same next letter form one contiguous block of the sorted list, and all blocks at a level have the same size. Integer division by that size tells you which block position k - 1 falls into.
Why is this problem tagged as backtracking?
The expected first solution is a DFS that builds the strings in order and stops at the k-th. Since k is at most 100 that is fast, and the block-counting method is the same search with whole subtrees skipped at once.
How many happy strings of length n are there?
3 x 2^(n-1). For n = 10 that is 1536.