Improved algorithm