Optimize algorithm to work efficiently for large inputs