Optimize with caching or hash maps | Amazon Interview Question