#K50932. Rearrange String with Substring Constraints
Rearrange String with Substring Constraints
Rearrange String with Substring Constraints
You are given a string s of length n consisting of lowercase English letters and an integer k. Your task is to rearrange the string so that in every contiguous substring of length k the number of distinct characters is minimized. In other words, the characters should be grouped as much as possible to reduce diversity in every block of length k.
Input Constraints:
- \(1 \leq k \leq n \leq 10^5\)
- The string s consists of lowercase English letters only.
Note: The rearranged string must have exactly the same frequency of each character as the original string.
Example:
- For \(n=6,\; k=3,\; s=\texttt{aabbcc}\), one valid answer is abcabc.
- For \(n=4,\; k=2,\; s=\texttt{aabb}\), one valid answer is abab.
- For \(n=9,\; k=3,\; s=\texttt{aaabbbccc}\), one valid answer is abcabcabc.
Your solution should read from stdin and write the result to stdout.
inputFormat
The first line of input contains two integers, \(n\) and \(k\), separated by a space.
The second line contains the string s of length \(n\>.
outputFormat
Output the rearranged string that minimizes the number of distinct characters in every contiguous substring of length \(k\).
## sample6 3
aabbcc
abcabc