learning elegant solution from one of the answers