Exclusive Elements - codepath/compsci_guides GitHub Wiki
Unit 3 Session 2 (Click for link to problem statements)
TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: List Manipulation, Iteration
U-nderstand
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?
- The function
exclusive_elements()
should take two integer lists lst1 and lst2 and return a new list that contains elements that are exclusive to each list (i.e., elements that are in lst1 but not in lst2, and vice versa).
HAPPY CASE
Input: lst1 = ["pooh", "roo", "piglet"], lst2 = ["piglet", "eeyore", "owl"]
Expected Output: ["pooh", "roo", "eeyore", "owl"]
Input: lst1 = ["pooh", "roo"], lst2 = ["piglet", "eeyore", "owl", "kanga"]
Expected Output: ["pooh", "roo", "piglet", "eeyore", "owl", "kanga"]
EDGE CASE
Input: lst1 = ["pooh", "roo", "piglet"], lst2 = ["pooh", "roo", "piglet"]
Expected Output: []
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that iterates through both lists to find elements unique to each list, and then combines these elements into a new list.
1. Define the function `exclusive_elements(lst1, lst2)`.
2. Initialize two empty lists: `exclusive_lst1` and `exclusive_lst2`.
3. Use a for loop to iterate through each item in `lst1`.
a. If the item is not in `lst2`, append it to `exclusive_lst1`.
4. Use a for loop to iterate through each item in `lst2`.
a. If the item is not in `lst1`, append it to `exclusive_lst2`.
5. Return the concatenation of `exclusive_lst1` and `exclusive_lst2`
⚠️ Common Mistakes
- Not correctly identifying the elements that are exclusive to each list.
- Forgetting to handle cases where the lists may be empty.
I-mplement
Implement the code to solve the algorithm.
def exclusive_elements(lst1, lst2):
exclusive_lst1 = []
exclusive_lst2 = []
# Find elements in lst1 that are not in lst2
for item in lst1:
if item not in lst2:
exclusive_lst1.append(item)
# Find elements in lst2 that are not in lst1
for item in lst2:
if item not in lst1:
exclusive_lst2.append(item)
return exclusive_lst1 + exclusive_lst2