Rothesay interview question

Leetcode style question. Medium difficulty.