complete implementation of simple but space efficient version