Optimize with a cache/hash map | Amazon Interview Question