working on the mem efficient implementation