reimplement using sort and iteration
sol of 2.60