How to improve the time complexity?