Microsoft Interview Question

A hard question from leetcode