An O(n) approach after the sorting which itself is O(n lg n)