Full solution with comments