LeetCode 1415, Medium. Topics: String, Backtracking. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 30 parametrized pytest cases, and a playground notebook:
Problem
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.
Examples
Constraints
1 <= n <= 10
1 <= k <= 100
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026