The k-th Lexicographical String of All Happy Strings of Length n (LeetCode 1415): Solution and Explanation

Medium
String
Backtracking

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

  1. Set block = 2^(n-1). If k > 3 * block, return the empty string.
  2. Make k zero-based with k -= 1. The first letter is "abc"[k // block].
  3. While block > 1: set k %= block (the offset inside the chosen block) and halve block.
  4. The next letter is one of the two letters different from the last one, in alphabetical order. Pick index k // block.
  5. Return the letters joined together.

Step-by-step example

n = 3, k = 9
  1. There are 3 x 2^2 = 12 happy strings of length 3. Since 9 <= 12, the answer exists.
  2. k - 1 = 8 and block = 4. 8 // 4 = 2, so the string is in the third block: it starts with 'c'.
  3. Offset 8 % 4 = 0, block = 2. After 'c' the options are 'a' and 'b'. 0 // 2 = 0 picks 'a': prefix "ca".
  4. Offset 0 % 2 = 0, block = 1. After 'a' the options are 'b' and 'c'. 0 // 1 = 0 picks 'b': prefix "cab".
  5. 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)
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One division and one remainder per letter, and there are n letters.

Space

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.