Updated old solution to work faster (2 functions)