Improved algorithm even further by accounting for special cases more intelligently