Given a string **S**, the task is to find the largest lexicographical string with no more than **K** consecutive occurrence of an element by either re-arranging or deleting the elements.

**Examples:**

```
Input: S = “baccc”
K = 2
Output: Result = “ccbca”
Explanation: Since K=2, a maximum of 2 same characters can be placed consecutively.
No. of ‘c’ = 3.
No. of ‘b’ = 1.
No. of ‘a’ = 1.
Since the largest lexicographical string has to be printed, therefore, the answer is “ccbca”.
Input: S = “xxxxzaz”
K = 3
Output: result = “zzxxxax”
```

**Approach:**

- Form a frequency array of size 26, where index i is chosen using (character in string – ‘a’).
- Initialize an empty string to store corresponding changes.
- for i=25 to 0, do:

- If frequency at index i is greater than k, then append (i + ‘a’) K-times. Decrease frequency by K at index i.find the next greatest priority element and append to answer and decrease frequency at respective index by 1.
- If frequency at index i is greater than 0 but less than k, then append (i + ‘a’) times it’s frequency.
- If frequency at index i is 0, then that index cannot be used to form an element and therefore check for next possible highest priority element.

#algorithms #arrays #greedy #hash #strings #lexicographic-ordering

14.65 GEEK