Rakuten interview question

A algorithm problem, medium difficulty