Skip to main content
Back to problems
Leetcode
Medium
Combinatorics
Backtracking
Recursion
Google
The K-th Lexicographical String Of All Happy Strings Of Length N

Find the k-th lexicographically smallest happy string of length n, or return an empty string if fewer than k exist.

Acceptance 100%
Problem Statement

Given two integers nn and kk, consider all happy strings of length nn formed using only the letters a, b, and c.

A string is happy if no two adjacent characters are the same.

Your task is to return the kk-th string in lexicographical order among all happy strings of length nn. If there are fewer than kk such strings, return an empty string.

A string s is lexicographically smaller than string t if at the first position where they differ, the character in s comes before the character in t alphabetically.

Input Format

Input

  • Two integers n and k.

Interpretation

  • n is the required length of the happy string.
  • k is 1-indexed and refers to the lexicographical rank among all valid strings.

Output Format

Output

  • Return the kk-th lexicographically smallest happy string of length n.
  • If it does not exist, return an empty string "".

Constraints

  • 1n101 \le n \le 10
  • 1k1001 \le k \le 100
  • Only characters a, b, and c may be used.
  • Adjacent characters in the string must always be different.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 1, k = 3

Output

c

Explanation

The happy strings of length 1 in order are: a, b, c. The 3rd one is c.

Example 2

Input

n = 3, k = 9

Output

cab

Explanation

The happy strings of length 3 in lexicographical order are: aba, abc, aca, acb, bab, bac, bca, bcb, cab, cac, cba, cbc. The 9th string is cab.

Show 1 more example

Example 3

Input

n = 3, k = 13

Output

Explanation

There are only 12 happy strings of length 3, so the 13th does not exist.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.