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

A happy string uses only 'a', 'b' and 'c' with no two equal neighbours. Given `n` and `k`, list all happy strings of length `n` in lexicographical order and return the `k`-th one (1-indexed), or an empty string if there are fewer than `k`.

30:00

The k-th Lexicographical String of All Happy Strings of Length n
medium
Free written solution
Topics
Companies

A happy string uses only 'a', 'b' and 'c' with no two equal neighbours. Given n and k, list all happy strings of length n in lexicographical order and return the k-th one (1-indexed), or an empty string if there are fewer than k.

Example 1:
Input: {"n":1,"k":3}
Output: c
Constraints:
  • 1≤n≤101 \leq n \leq 10

  • 1≤k≤1001 \leq k \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":1,"k":3}

The first letter has 3 choices and every later letter has 2 (anything but the previous one), so there are 3 x 2^0 = 3 happy strings of length 1. Each first letter owns a block of 1.

all 3 happy strings of length 1, sorted

a...

b...

c...

0

2

answer, one letter per level

Variables
VariableValue
k3
block1
total3
DepthFunction Call
Stack empty
0/3