refactored problem3, same runtime though