Algorithm 1 (coursera.org)