What is the memory complexity of this algorithm? And can you give me an algorithm with better memory complexity?