Solution by Andrew Mehta.