Algorithm exercise