Post

1516 The K Th Lexicographical String Of All Happy Strings Of Length N

1516 The K Th Lexicographical String Of All Happy Strings Of Length N

The k-th Lexicographical String of All Happy Strings of Length n image

A happy string is a string that:

1
2
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 kth string of this list or return an empty string if there are less than k happy strings of length n.

 

Example 1:

1
2
3
4
5
**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:

1
2
3
4
5
**Input:** n = 1, k = 4
**Output:** ""
**Explanation:** There are only 3 happy strings of length 1.

Example 3:

1
2
3
4
5
**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 9th string = "cab"

 

Constraints:

1
2
1 <= n <= 10
1 <= k <= 100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

class Solution:
    def getHappyString(self, n: int, k: int) -> str:
        """
            a ab abc abca abcb abcab abcac abcaba abcabc abcaca abcacb
        """

        def recurse(s , n):
            if n == 0:
                return [s]
            res = []
            a1 , a2, a3 = [] , [], []
            if s == "":
                a1 = recurse( "a" , n - 1)
                a2 = recurse( "b" , n - 1)
                a3 = recurse( "c" , n - 1)
                
                
            if len(s) > 0 and s[-1] == "a":
                a1 = recurse( s + "b" , n - 1)
                a2 = recurse( s + "c" , n - 1)

            if len(s) > 0 and s[-1] == "b":
                a1 = recurse( s + "a" , n - 1)
                a2 = recurse( s + "c" , n - 1)

            if len(s) > 0 and s[-1] == "c":
                a1 = recurse( s + "a" , n - 1)
                a2 = recurse( s + "b" , n - 1)
            
            for n in a1:
                res.append(n)

            for n in a2:
                res.append(n)

            for n in a3:
                res.append(n)
            return res
        x = recurse("", n)
        #print(x)
        return x[k-1] if k-1 < len(x) else ""
                



This post is licensed under CC BY 4.0 by the author.