TikTok Interview Question

a leetcode hard problem. on hackerrank