The k-th Lexicographical String of All Happy Strings of Length n Problem
Description
LeetCode Problem 1415.
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 ofifrom1tos.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 kth string of this list or return an empty string if there are less than k happy strings of length n.
Example 1:
Input: n = 1, k = 3
Output: "c"
Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4
Output: ""
Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9
Output: "cab"
Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]. You will find the 9^th string = "cab"
Constraints:
1 <= n <= 101 <= k <= 100
Solution
Approach: Count the Strings Under Each Prefix
We can build the answer letter by letter without listing all happy strings.
The first letter can be any of a, b, c, and every later letter has exactly 2 choices (anything except the previous letter). So there are 3 · 2^(n−1) happy strings of length n, and each choice of the first letter starts a block of block = 2^(n−1) of them. If k is larger than 3 · block, the answer is the empty string.
Otherwise, switch to a 0-based rank k − 1 and go through the positions in lexicographic order:
- First letter: the strings are grouped by it in the order
a,b,c, so it is"abc"[rank / block], and the rank inside that group isrank % block. - Each next letter: halve
block. The two allowed letters, in alphabetical order, each start a group ofblockstrings, so pick the first one ifrank / blockis0and the second if it is1, then keeprank % block.
For example, n = 3, k = 9: rank 8, block 4, so the first letter is "abc"[2] = c and the rank becomes 0; then a (rank 0 / 2 = 0 among a, b), then b (rank 0 / 1 = 0 among b, c), giving "cab".
Complexity: O(n) time and O(n) space for the answer. (Generating the strings in order with a DFS and stopping at the k-th also works, since there are at most 1536 of them.)
class Solution:
def getHappyString(self, n: int, k: int) -> str:
block = 1 << (n - 1) # happy strings that start with a given letter
if k > 3 * block:
return ""
k -= 1 # 0-based rank
ans = ["abc"[k // block]]
k %= block
for _ in range(n - 1):
block //= 2 # each of the two allowed letters covers half of what is left
options = [c for c in "abc" if c != ans[-1]]
ans.append(options[k // block])
k %= block
return "".join(ans)