semi slow solution. 3 sec without pre-sorting. hmm.