Amazon interview question

Leetcode-style algorithm question. Was about medium difficulty.