Meta Interview Question

leetcode qtn, med - hard version