TikTok Interview Question

A leetcode hard question with follow up question