Solution for problem D