Unit 4 Session 1 Standard (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?
Q: What is the output?
Q: How should ties be handled when multiple memes have the same average reposts?
Q: What should be done if the time range is invalid (e.g., start_day
> end_day
)?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate over each meme in the list, calculate the average reposts for the specified time range, and track the meme with the highest average.
1) Initialize `max_average` to a value that cannot be a valid average, such as -1.
2) Initialize `trending_meme` to `None` to store the name of the meme with the highest average reposts.
3) For each meme in the list:
a) Extract the repost counts within the specified time range.
b) Calculate the average of these repost counts.
c) If this average is higher than `max_average`, update `max_average` and `trending_meme`.
4) After processing all memes, return the `trending_meme`.
**⚠️ Common Mistakes**
- Incorrectly slicing the repost counts, leading to wrong averages.
- Forgetting to account for the possibility of a tie in averages, although the function naturally handles this by selecting the first occurrence.
def find_trending_meme(memes, start_day, end_day):
max_average = -1
trending_meme = None
for meme in memes:
reposts = meme["reposts"][start_day:end_day + 1]
average_reposts = sum(reposts) / len(reposts)
if average_reposts > max_average:
max_average = average_reposts
trending_meme = meme["name"]
return trending_meme