Toptal interview question

Algorithm question, based on leetcode