Along a straight hedge, n fireflies are lined up and numbered 1 to n in order. Firefly i emits a single flash of one lowercase-letter color, given by s[i]. Two fireflies emitting the SAME color are said to be within resonance of each other if the number of positions between them (their index gap) is at most k, measured in the CURRENT line-up -- not the original numbering, since the line-up shrinks over time as described below.
Whenever a resonant same-color pair exists anywhere in the current line-up, the later (right-hand) firefly of that pair is absorbed into the earlier (left-hand) one and permanently leaves the line; the remaining fireflies then close the gap and are re-numbered 1 through the new count, in order, exactly as if that firefly's flash were deleted from a string. If several resonant pairs exist at once, the one whose earlier (left-hand) firefly currently sits furthest to the left is absorbed first; if more than one such pair shares that same left-hand firefly, the one with the nearest right-hand partner is absorbed first. This absorption repeats, always re-checking the current (possibly changed) line-up for new resonant pairs after every single absorption, until no resonant same-color pair remains anywhere.
Given the initial flash colors and k, determine the final surviving sequence of flash colors, left to right.
A single line: the string of surviving flash colors, left to right, after no resonant pair remains.
Example 1
Input
aabca 2
Expected
abca
Explanation
The two 'a' flashes sit at positions 1 and 2, a gap of 1 (<= k=2), so the second is absorbed into the first, leaving 'a','b','c','a' -> "abca". The remaining 'a' flashes are now at positions 1 and 4, a gap of 3, beyond k=2, so no further absorption happens.
Example 2
Input
yybyzybz 2
Expected
ybzybz
Explanation
The 'y' flashes at positions 1 and 2 resonate (gap 1) and absorb, shrinking the line to "ybyzybz". Re-numbered, the surviving 'y' flashes now sit at positions 1 and 3 -- a gap of 2, newly within k=2 even though they were not originally that close -- so they resonate too and absorb, leaving "ybzybz". No same-colored pair is now within a gap of 2, so absorption stops there.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →