Completed the second approach for problem