This page is still under construction.

Parts of this page are still being built. What you see may change.

Binary Search Tree Code

Interview

Time limit1sMemory limit128 MB

Summary
Given n and k, output the n-th preorder string among all BSTs built from the first k letters, listed in alphabetical order.
Level

Medium7 of 10

Topics
Tree, Recursion, Combinatorics, Binary search
Solved
No attempts yet

Problem

A binary tree is either empty, or it consists of one vertex together with two trees linked to it. These two trees are called the left subtree and the right subtree. Each vertex holds one lowercase letter of the English alphabet. The vertex that is not a subtree of any other vertex is called the root.

A tree is a binary search tree (BST) if the following condition holds at every vertex: all letters in the left subtree precede, in alphabetical order, the letter at the root, and all letters in the right subtree follow the letter at the root.

The code of a BST is defined as follows.

  • If the tree is empty, the code is the empty string (0 letters).
  • Otherwise, it is the letter at the root, followed by the code of the left subtree, followed by the code of the right subtree.

Consider every BST that has kk vertices holding the first kk letters of the English alphabet. Write the codes of all such trees in alphabetical order. The nn-th code in that list is called the (n,k)(n, k)-code.

For example, there are exactly 14 BSTs with 4 vertices, and their codes in alphabetical order are:

abcd abdc acbd adbc adcb bacd badc cabd cbad dabc dacb dbac dcab dcba

The string badc is the (7,4)(7, 4)-code, and it corresponds to the BST shown below.

Binary search tree corresponding to the (7, 4)-code badc

Write a program that:

  • reads the two integers nn and kk from standard input,
  • finds the (n,k)(n, k)-code, and
  • writes it to standard output.

Input

The first and only line of standard input contains two positive integers nn and kk, separated by a single space, with 1≤k≤191 \le k \le 19. The value nn is not greater than the total number of codes of BSTs with kk vertices.

Output

The first and only line of standard output must contain exactly one word, written in lowercase letters, which is the (n,k)(n, k)-code.

Examples3

  1. Example 1

    Input
    11 4
    
    Expected output
    dacb
    
  2. Example 2

    Input
    7 4
    
    Expected output
    badc
    
  3. Example 3

    Input
    1 1
    
    Expected output
    a