solution for algorithm problem