LeetCode Day 28: k-th Lexicographical Happy String

Day 28/30 – LeetCode streak Problem: The k-th Lexicographical String of All Happy Strings of Length n A happy string is length 'n' over '{a,b,c}' with no two adjacent characters equal. Core idea * Total happy strings of length 'n':  * First character: 3 choices ('a','b','c').  * Each of the remaining 'n-1' positions: 2 choices (anything different from the previous character).  * So 'total = 3 * 2^(n-1)'. If 'k > total', the answer is an empty string. * Instead of generating all strings, we can index them directly:  * Fixing the first character divides the list into blocks.  * Each first character corresponds to a block of '2^(n-1)' strings.  * Compute 'block = 1 << (n-1)'.  * 'firstIdx = (k-1) / block' → '0 → a', '1 → b', '2 → c'.  * 'rem = (k-1) % block' determines the remaining 'n-1' choices. * For each remaining position:  * Look at the previous character.  * The next character must be one of the two letters different from it, taken in lexicographic order.  * Use bits of 'rem' to choose between the smaller or larger valid option. This lets us map 'k' directly to the correct happy string in 'O(n)' time without generating all combinations. Day 28 takeaway: Happy strings follow a clean combinatorial pattern of '3 * 2^(n-1)'. Treating the suffix as a binary decision sequence lets you construct the k-th string directly instead of using backtracking or BFS. #leetcode #dsa #java #strings #combinatorics #consistency

  • graphical user interface

To view or add a comment, sign in

Explore content categories