Goldman Sachs interview question

Medium difficult leetcode style problem.