. Let's define an array B as S concatenated with itself m times, where m is the smallest integer such that m(r−l+1)≥K
. Next, let's sort B and define X=BK, i.e. as a K-th smallest element of B. Note that |B|≥K.
Are you actually generating B and sorting it?
Because I think you only need to sort S, and do a bit of math.