nonrecursive solution