TikTok Interview Question

Leetcode question. Then try to improve time complexity.