correct code but large memory required