Added smart method with nlogn complexity