Non-recursive solution with some optimizations