Optimized algorithm