Goldman Sachs interview question

Standard leetcode question to code