fixing memory leak
complete algo