Working solution for Problem 2