Amazon Interview Question

Leetcode-style algorithm question. Was about medium difficulty.