Snap interview question

Medium-level Leetcode style question on HackerRank