Unit 4 Session 1 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What is the structure of the input?
"name"
key and a "materials"
key containing a list of strings.Q: What is the output?
Q: What should the function return if no materials are trending?
Q: Are there any constraints on the input, such as the presence of the "materials"
key in each dictionary?
"name"
key and a "materials"
key with corresponding values.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Count the occurrences of each material using a dictionary, then iterate through the dictionary to identify and return the materials that appear more than once.
1) Initialize an empty dictionary called `material_count`.
2) For each `brand` in `brands`:
a) For each `material` in `brand["materials"]`:
i) If the `material` is already in `material_count`, increment its count.
ii) If the `material` is not in `material_count`, add it with a count of 1.
3) Initialize an empty list called `trending_materials`.
4) For each `material, count` in `material_count.items()`:
a) If `count` > 1, append the `material` to `trending_materials`.
5) Return the `trending_materials` list.
**⚠️ Common Mistakes**
- Forgetting to correctly initialize the material count when encountering a material for the first time.
- Not checking that a material appears more than once before marking it as trending.
def find_trending_materials(brands):
material_count = {}
trending_materials = []
for brand in brands:
for material in brand["materials"]:
if material in material_count:
material_count[material] += 1
else:
material_count[material] = 1
for material, count in material_count.items():
if count > 1:
trending_materials.append(material)
return trending_materials