implemented logic for algorithm