Faster solution instead of sorting