Google interview question

Hard leetcode style problem.