JCSU Unit 2 Problem Set 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: nums = [1, 2, [3, 4], [5], 6] target = 7 Output: [(1, 6), (2, 5), (3, 4)] Explanation: The pairs of numbers that add up to 7 are (1, 6), (2, 5), and (3, 4).
EDGE CASE Input: nums = [] target = 10 Output: [] Explanation: An empty list results in no pairs.
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 finding problems, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Flatten the nested list into a single list, then use a set to track seen numbers. For each number in the flattened list, calculate its complement with respect to the target sum. If the complement exists in the set, add the pair to the result.
flattened
.
nums
:
flattened
with its elements.flattened
.pairs
and an empty set seen
.flattened
:
target - num
.seen
, add the pair (complement, num)
to pairs
.seen
.pairs
.Implement the code to solve the algorithm.
def find_pairs(nums, target):
# Flatten the nested list into a single list of integers
flattened = []
for item in nums:
if isinstance(item, list): # Check if the item is a sublist
flattened.extend(item) # Extend the flattened list with elements from the sublist
else:
flattened.append(item) # Append the item directly if it's not a sublist
pairs = [] # Initialize a list to store the pairs
seen = set() # Use a set to track visited numbers for efficiency
for num in flattened:
complement = target - num # Calculate the complement for the current number
if complement in seen: # Check if the complement is in the set of seen numbers
pairs.append((complement, num)) # Add the pair to the result list
seen.add(num) # Add the current number to the set of seen numbers
return pairs # Return the list of pairs
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
Example 2:
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is the total number of elements in the nested lists.