faster implementation that is still too slow when S and L has lots of
repetetion