Google Interview Question

Hard leetcode style problem.