Optimized solution by removing the reversed string var (dont need it) and handling cases with spaces