Given a string **S** and an integer **K**. The task is to find lexicographically largest subsequence of S, say T, such that every character in T must occur at least K times.

**Examples:**

Input : S = "banana", K = 2. Output : nn Possible subsequence where each character exists at least 2 times are: From the above subsequences, "nn" is the lexicographically largest.

The idea is to solve greedily the above problem. If we want to make the subsequence lexicographically largest, we must give priority to lexicographically larger characters. ‘z’ is the largest character, let suppose z occurs f_{z} times in S. If f_{z} >= K, append ‘z’z k times in the string T and keep removing characters from the left of S until all the z’s are removed. Apply the strategy with ‘y’, ‘w’, ….., ‘a’. In the end you will find the answer.

Let see an example. Suppose S = “zzwzawa” and K = 2. Start with the largest character ‘z’. Here f_{z} = 3 >= K. So T will become “zzz” and we will remove letters from the left of S until all the z’s are removed. So now S will became “awa”. Next largest is ‘y’ but that occurs 0 times in k so we will skip it. We will skip ‘w’, ‘v’ etc also until we go to ‘a’ which occurs 2 times. Now T will become “zzzaa” and S will become a empty string. Our answer is “zzzaa”.

Below is implementation of this approach:

## leave a comment

## 0 Comments