add a sort based solution O(nlogn)