Reddit Interview Question

Leetcode question, followed by "what is the runtime/space complexity" and "how would you optimize this?"