← All problems

1415. The K Th Lexicographical String of All Happy Strings of Length N

MediumOpen on LeetCodeProblem statement

Problem Statement

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

Medium


A happy string is a string that:

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"

 

Constraints:

Java

Source file
class Solution {
    int count = 0;
    String ans = null;

    public String getHappyString(int n, int k) {
        char[] cs = new char[n];
        dfs(0, n, k, cs);
        return ans == null ? "" : ans;
    }

    private void dfs(int len, int n, int k, char[] cs) {
        // System.out.println(Arrays.toString(cs));
        if (len == n) {
            if (++count == k)
                ans = new String(cs);
            return;
        }
        if (count >= k)
            return;
        for (int i = 0; i < 3; i++) {
            char c = (char) ('a' + i);
            if (len != 0 && cs[len - 1] == c)
                continue;
            cs[len] = c;
            dfs(len + 1, n, k, cs);
        }
    }
}