##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1415.html

# 1415. The k-th Lexicographical String of All Happy Strings of Length n (Medium)

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 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 9th string = "cab"


Example 4:

Input: n = 2, k = 7
Output: ""


Example 5:

Input: n = 10, k = 100
Output: "abacbabacb"


Constraints:

• 1 <= n <= 10
• 1 <= k <= 100

Related Topics:
Backtracking

## Solution 1. Naive Solution

// OJ: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
// Time: O(3^N)
// Space: O(1)
class Solution {
int i = s.size() - 1;
for (; i >= 0; --i) {
if (s[i] == 'c') {
s[i] = 'a';
continue;
}
s[i]++;
break;
}
return i == -1 ? (s = "") : s;
}
bool valid(string &s) {
int i = s.size() - 1;
for (; i > 0; --i) {
if (s[i] == s[i - 1]) return false;
}
return true;
}
string next(string &s) {
do {
} while (s != "" && !valid(s));
return s;
}
public:
string getHappyString(int n, int k) {
string ans;
for (int i = 0; i < n; ++i) ans.push_back(i % 2 == 0 ? 'a' : 'b');
while (--k) {
ans = next(ans);
if (ans == "") return "";
}
return ans;
}
};


## Solution 2. DFS

// OJ: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
// Time: O(3^N). It should be smaller than O(3^N) since there are cases skipped earlier, but should be greater than O(NK).
// Space: O(NK)
// Ref: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/585557/C%2B%2B-Straightforward-DFS.-Skip-appending-same-char.
class Solution {
vector<string> ans;
void dfs(string &cur, int n, int k) {
if (ans.size() == k) return;
if (cur.size() == n) {
ans.push_back(cur);
return;
}
for (int i = 0; i < 3; ++i) {
if (cur.size() && cur.back() == 'a' + i) continue;
cur.push_back('a' + i);
dfs(cur, n, k);
cur.pop_back();
}
}
public:
string getHappyString(int n, int k) {
string cur;
dfs(cur, n, k);
return ans.size() == k ? ans.back() : "";
}
};

• class Solution {
public String getHappyString(int n, int k) {
if (n == 1) {
if (k <= 3)
return String.valueOf((char) ('a' + k - 1));
else
return "";
}
int max = 3 * (int) Math.pow(2, n - 1);
if (k > max)
return "";
int groupSize = max / 3;
int highest = (k - 1) / groupSize;
int index = (k - 1) % groupSize;
int[] array = toArray(highest, index, n);
StringBuffer sb = new StringBuffer();
char letter0 = (char) ('a' + array[0]);
sb.append(letter0);
char prevLetter = letter0;
for (int i = 1; i < n; i++) {
char letter = getNextLetter(array[i], prevLetter);
sb.append(letter);
prevLetter = letter;
}
return sb.toString();
}

public int[] toArray(int highest, int index, int length) {
int[] array = new int[length];
array[0] = highest;
int position = length - 1;
while (index > 0) {
array[position] = index % 2;
index /= 2;
position--;
}
return array;
}

public char getNextLetter(int num, char prevLetter) {
char letter = (char) ('a' + num);
if (letter >= prevLetter)
letter++;
return letter;
}
}

############

class Solution {
private List<String> ans = new ArrayList<>();

public String getHappyString(int n, int k) {
dfs("", n);
return ans.size() < k ? "" : ans.get(k - 1);
}

private void dfs(String t, int n) {
if (t.length() == n) {
return;
}
for (char c : "abc".toCharArray()) {
if (t.length() > 0 && t.charAt(t.length() - 1) == c) {
continue;
}
dfs(t + c, n);
}
}
}

• // OJ: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
// Time: O(3^N)
// Space: O(1)
class Solution {
int i = s.size() - 1;
for (; i >= 0; --i) {
if (s[i] == 'c') {
s[i] = 'a';
continue;
}
s[i]++;
break;
}
return i == -1 ? (s = "") : s;
}
bool valid(string &s) {
int i = s.size() - 1;
for (; i > 0; --i) {
if (s[i] == s[i - 1]) return false;
}
return true;
}
string next(string &s) {
do {
} while (s != "" && !valid(s));
return s;
}
public:
string getHappyString(int n, int k) {
string ans;
for (int i = 0; i < n; ++i) ans.push_back(i % 2 == 0 ? 'a' : 'b');
while (--k) {
ans = next(ans);
if (ans == "") return "";
}
return ans;
}
};

• class Solution:
def getHappyString(self, n: int, k: int) -> str:
def dfs(t):
if len(t) == n:
ans.append(t)
return
for c in 'abc':
if t and t[-1] == c:
continue
dfs(t + c)

ans = []
dfs('')
return '' if len(ans) < k else ans[k - 1]

############

class Solution:
def getHappyString(self, n: int, k: int) -> str:
happies = []
self.genHappies(n, "", happies)
if k > len(happies):
return ""
return happies[k - 1]

def genHappies(self, n, path, happies):
if len(path) == n:
happies.append(path)
return
for x in ['a', 'b', 'c']:
if not path or path[-1] != x:
self.genHappies(n, path + x, happies)