#K95142. Rearrange String with Minimum Separation
Rearrange String with Minimum Separation
Rearrange String with Minimum Separation
You are given a string S and an integer K. Your task is to determine whether it is possible to rearrange the characters of S such that the same characters are at least K
distance apart. In other words, if the rearranged string is denoted by S' and S'[i] represents the character at position i (0-indexed), then for any two occurrences of the same character at positions i and j (S'[i]=S'[j]
and i!=j
), the distance between them should satisfy:
\( | i - j | \ge K \)
If such a rearrangement exists, output YES
, otherwise output NO
.
Note: When K = 1
, any arrangement of the string is valid.
inputFormat
The input is read from standard input. The first line contains an integer T
representing the number of test cases. Each of the following T
lines contains a string S and an integer K separated by whitespace.
Example:
5 aabbcc 2 aaabc 3 abcdef 3 aaa 2 a 1
outputFormat
For each test case, output a single line containing YES
if it is possible to rearrange the string so that any two identical characters are at least K
positions apart, or NO
otherwise. The output should be written to standard output.
Example:
YES NO YES NO YES## sample
5
aabbcc 2
aaabc 3
abcdef 3
aaa 2
a 1
YES
NO
YES
NO
YES
</p>