correct implementation and memory/timing efficient