This page is still under construction.

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

Lexicographically Minimal Subsequence

Interview

Time limit2sMemory limit512 MB

Summary
Given a string s and an integer k, output the lexicographically smallest length-k subsequence of s.
Level

Medium5 of 10

Topics
Stack, Greedy, String, Two pointers
Solved
No attempts yet

Problem

You are given a string ss and an integer kk. Find the lexicographically minimal subsequence of ss whose length is kk.

Input

The first line contains a string ss (1≤∣s∣≤1061 \le |s| \le 10^6). It consists of lowercase Latin letters.

The second line contains an integer kk (1≤k≤∣s∣1 \le k \le |s|), the length of the resulting subsequence.

Output

Output the lexicographically minimal subsequence of ss whose length is kk.

Notes

A string sp1sp2…spks_{p_{1}}s_{p_{2}}\dots s_{p_{k}} (1≤p1<p2<⋯<pk≤∣s∣)(1 \le p_{1} < p_{2} < \dots < p_{k} \le |s|) is called a subsequence of string ss.

A string x=x1x2…xkx = x_{1}x_{2}\dots x_{k} is lexicographically less than a string y=y1y2…yky = y_{1}y_{2}\dots y_{k} if there exists a number ii (1≤i≤k)(1 \le i \le k) such that x1=y1,x2=y2,…,xi−1=yi−1x_{1} = y_{1}, x_{2} = y_{2}, \ldots , x_{i-1} = y_{i-1} and xi<yix_{i} < y_{i}. Characters in strings are compared by their ASCII codes.

Examples1

  1. Example 1

    Input
    bcaabac
    4
    
    Expected output
    aaac