TikTok interview question

a leetcode hard problem. on hackerrank