slight change to stackoverflow algorithm