← Home

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

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
backtrackingC++Markdown
141

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1415. The k-th Lexicographical String of All Happy Strings of Length n, the solution in this repository is mainly a backtracking solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: backtracking.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, getHappyString.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 92 ms, faster than 43.96% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
02//Memory Usage: 24.6 MB, less than 100.00% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
03class Solution {
04public:
05    int n;
06    
07    void backtrack(vector<vector<char>>& pers, vector<char>& per, vector<char>& chars){
08        if(per.size() == n){
09            pers.push_back(per);
10        }else{
11            for(char c : chars){
12                if(per.size() > 0 && per[per.size()-1] == c){
13                    continue;
14                }
15                per.push_back(c);
16                backtrack(pers, per, chars);
17                per.pop_back();
18            }
19        }
20    };
21    
22    string getHappyString(int n, int k) {
23        int count = 3 * (1 << (n-1));
24        if(k > count) return "";
25        
26        this->n = n;
27        
28        vector<vector<char>> pers;
29        vector<char> per;
30        vector<char> chars = {'a', 'b', 'c'};
31        
32        backtrack(pers, per, chars);
33        
34        // for(vector<char> p : pers){
35        //     for(char c : p){
36        //         cout << c;
37        //     }
38        //     cout << endl;
39        // }
40        // cout << endl;
41        
42        string ans = "";
43        for(char c : pers[k-1]){
44            ans += c;
45        }
46        
47        return ans;
48    }
49};
50
51//Math
52//https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/585590/C%2B%2B-DFS-and-Math
53//Runtime: 0 ms, faster than 100.00% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
54//Memory Usage: 5.8 MB, less than 100.00% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
55//time: O(N), space: O(1)
56class Solution {
57public:
58    string getHappyString(int n, int k) {
59        //there are total 3*pow(2, n-1) happy strings
60        int prem = 1 << (n-1);
61        if(k > 3 * prem) return "";
62        
63        //k falls in (1) [1, prem] -> 'a' (2) [prem+1, prem*2] -> 'b' (3) [prem*2+1, prem*3] -> 'c'
64        //(k-1)/prem: which interval(0,1 or 2) current char is in
65        string ans(1, 'a' + (k-1)/prem);
66        
67        // cout << k << " " << prem << " " << (char)('a'+(k-1)/prem) << endl;
68        
69        // while(prem > 1){
70        while(--n > 0){
71            //we have consumed one position
72            /*
73            (k-1)/prem: which interval current char is in
74            prem: each interval's length
75            previous intervals have taken "(k - 1) / prem * prem" spaces,
76            so we need to remove them
77            
78            for 1st iteration, possible intervals are (0,1,2) (we can choose from a, b or c)
79            for later iteration, possible intervals are (0,1) (we can only choose two character different from last character)
80            */
81            k -= (k - 1) / prem * prem;
82            prem >>= 1;
83            /*
84            n = 3
85            ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab", "cac", "cba", "cbc"]
86            
87            for interval 0, choose from a or b
88            for interval 1, choose from b or c
89            */
90            // cout << k << " " << prem << " " << (k-1)/prem << endl;
91            ans += (k - 1) / prem == 0 ? 'a' + (ans.back() == 'a') : 'b' + (ans.back() != 'c');
92        }
93        
94        return ans;
95    }
96};
97
98//DFS
99//https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/585590/C%2B%2B-DFS-and-Math
100//Runtime: 0 ms, faster than 100.00% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
101//Memory Usage: 5.9 MB, less than 100.00% of C++ online submissions for The k-th Lexicographical String of All Happy Strings of Length n.
102//time: O(N*k), space: O(N)
103class Solution {
104public:
105    string getHappyString(int n, int& k, int l = 0, char last = '\0') {
106        //l: the length of building string
107        //last: last character in the building string
108        //note that k is passed by reference
109        if(l == n){
110            //we have built a happy string
111            k--;
112        }else{
113            for(char cur = 'a'; cur <= 'c'; cur++){
114                if(cur == last) continue;
115                string res = getHappyString(n, k, l+1, cur);
116                if(k == 0){
117                    return string(1, cur) + res;
118                }
119            }
120        }
121        return "";
122    }
123};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.