We’ll end with a classic interview question: given a list of integers and a “target” integer, return a pair of indices whose values sum to the target.
nums = [4, 2, 8, 9, 6] target = 8 pair_sum(nums, target) # nums + nums == 8 # [1, 4] pair_sum(nums, 17) # nums + nums == 17 # [2, 3] pair_sum(nums, 99) # no pair sum exists... # None
- Are there constraints on time or space efficiency?
- No! Any solution will do.
- Can the numbers be negative or 0?
- Yes! Your solution should handle those inputs.
- Does the order of indices matter?
- The earlier index comes first in the return list.
- Do we return all pairs that match a solution?
- No! The first one that your solution finds will do!
Write a function
pair_sum(), which has two parameters:
pair_sum() should return a list containing a pair of indices whose values sum to
If no such pair of indices exists, return