Solution Updated: A simpler solution using recursion.