Fixed edge case bug with algorithm