Microsoft interview question

Medium problem in leetcode, usually a random one.