Goldman Sachs Interview Question

Medium difficult leetcode style problem.