Shorter solution thanks to Andres Almiray