Problem Description
Given integers n and k, find the kth lexicographical happy string of length n. A happy string is composed only of the characters ['a', 'b', 'c'] and has no two adjacent characters that are the same. If there are fewer than k happy strings of length n, return an empty string.
Key Insights
- Use backtracking to generate all happy strings since n is small (1 <= n <= 10).
- Ensure lexicographical order by always processing characters in the order: 'a', 'b', 'c'.
- Check the last character to avoid adding a duplicate for consecutive positions.
- Stop the recursion once the kth string is obtained to save unnecessary computations.
Space and Time Complexity
Time Complexity: O(3^n) in the worst case, though early termination reduces the average case. Space Complexity: O(n) due to recursion depth and the space used to store each string.
Solution
We use a recursive backtracking algorithm to build strings character by character. At each recursion level, try adding 'a', 'b', or 'c' (in order) if it does not match the last character of the current string to maintain the happy string property. A counter tracks the number of valid strings generated; once the kth valid string is reached, store it and cancel further recursive calls. This method leverages the limited input range to remain efficient even though the worst-case complexity is exponential.