Rakuten Interview Question

A algorithm problem, medium difficulty