Unit 10 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
[]
.HAPPY CASE
Input: numbers = [3, 4, 7, 1, 2, 9, 8]
Output: [3, 8, 4, 7]
Explanation: 3 + 8 = 4 + 7
HAPPY CASE
Input: numbers = [1, 2, 3, 4, 5]
Output: [1, 4, 2, 3]
Explanation: 1 + 4 = 2 + 3
EDGE CASE
Input: numbers = [1, 2, 3]
Output: []
Explanation: No such integers exist.
EDGE CASE
Input: numbers = []
Output: []
Explanation: The list is empty, so no such integers exist.
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
For Pair Sum problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a hash map to store the sum of pairs of numbers and their corresponding indices. If the same sum is found again, return the pairs of numbers.
1) Initialize a hash map `map` to store sums and their corresponding pairs of numbers.
2) Iterate through each element `i` of the list `numbers`:
a) Iterate through each element `j` from `i+1` to the end of the list:
i) Calculate the sum of `numbers[i]` and `numbers[j]`.
ii) If the sum is already in `map`, return the existing pair and the current pair as the result.
iii) If the sum is not in `map`, store the sum with the pair `[numbers[i], numbers[j]]`.
3) If no such pair is found, return an empty list.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def find_sum_pair(numbers):
length = len(numbers)
map = {}
for i in range(length):
for j in range(i + 1, length):
sum = numbers[i] + numbers[j]
if sum in map:
return map[sum] + [numbers[i], numbers[j]]
else:
map[sum] = [numbers[i], numbers[j]]
return []
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume N
represents the length of the list numbers
.
O(N^2)
because we need to check all pairs of elements.O(N^2)
in the worst case for storing sums and their corresponding pairs in the hash map.