JPMorganChase Interview Question

Please explain how you came up with your code