Google interview question

Leetcode Medium - Hard question with multiple followups