TikTok interview question

A leetcode hard question with follow up question