recursive approach ran out of memory. rewrote iterative approach