Google interview question

LC medium (but quite hard)