Updated the solution with more comments