Amazon Interview Question

it was a leetcode hard question