revised the solution, needs to be more optimized