Microsoft interview question

Leetcode medium difficulty.