Working solution, solved recursively and iteratively