Unit 4 Session 2 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
n
podcast episodes from a list, in the order they were added.n
representing the number of most recent episodes to retrieve.n
episode IDs in the reverse order of their addition.n
is greater than the number of episodes?
n
is greater than the number of episodes, return all episodes in reverse order.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a stack to collect the episodes in the order they are added. Then, pop the most recent n
episodes from the stack to retrieve them in reverse order.
1) Initialize an empty list `stack`.
2) Iterate through the `episodes` list and push each episode onto the `stack`.
3) Initialize an empty list `recent_episodes`.
4) While `n` is greater than 0 and the stack is not empty:
a) Pop the top element from the stack and add it to `recent_episodes`.
b) Decrement `n` by 1.
5) Return `recent_episodes`, which now contains the most recent `n` episodes in the reverse order of their addition.
**⚠️ Common Mistakes**
- Forgetting to handle the case where `n` is greater than the number of episodes.
- Not reversing the order of the retrieved episodes.
- Assuming the list of episodes will always have at least `n` elements.
def get_recent_episodes(episodes, n):
stack = []
# Push all episodes onto the stack
for episode in episodes:
stack.append(episode)
# Pop the most recent `n` episodes
recent_episodes = []
while n > 0 and stack:
recent_episodes.append(stack.pop())
n -= 1
return recent_episodes
Example Usage:
episodes1 = ['episode1', 'episode2', 'episode3', 'episode4']
n = 3
print(get_recent_episodes(episodes1, n))
# Output: ['episode4', 'episode3', 'episode2']
episodes2 = ['ep1', 'ep2', 'ep3']
n = 2
print(get_recent_episodes(episodes2, n))
# Output: ['ep3', 'ep2']
episodes3 = ['a', 'b', 'c', 'd']
n = 5
print(get_recent_episodes(episodes3, n))
# Output: ['d', 'c', 'b', 'a']