Codepath

Reorder Podcast Episodes

Unit 4 Session 2 Standard (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the goal of the problem?
    • A: The goal is to reorder a list of podcast episodes based on a given list of indices representing the new order.
  • Q: What are the inputs?
    • A: The inputs are a list of episodes (stack) and a list of indices (indices) representing the new order.
  • Q: What are the outputs?
    • A: The output is a list of episodes reordered according to the specified indices.
  • Q: How are the indices provided?
    • A: The indices are 0-based and correspond to the new position of each episode in the list.
  • Q: What should be assumed about the inputs?
    • A: The list of episodes and the list of indices are of the same length, and each index in the indices list is unique and valid.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Create a new list to store the reordered episodes. Iterate through the original list and place each episode in the new list at the position specified by the corresponding index in the indices list.

1) Initialize a new list `reordered_stack` with the same length as `stack`, filled with `None`.
2) Iterate over the `stack` using its indices:
   a) For each index `i`, place `stack[i]` in `reordered_stack[indices[i]]`.
3) Return `reordered_stack`, which now contains the episodes in the new order.

**⚠️ Common Mistakes**

- Misinterpreting the `indices` list, leading to incorrect placements.
- Not correctly initializing the new list to store the reordered episodes.
- Assuming the indices list has duplicate or out-of-range values, which are not allowed by the problem constraints.

I-mplement

def reorder_stack(stack, indices):
    # Create a new list to store the reordered episodes
    reordered_stack = [None] * len(stack)

    # Place each episode in its new position
    for i, index in enumerate(indices):
        reordered_stack[index] = stack[i]

    return reordered_stack
Example Usage:

stack1 = ['Episode1', 'Episode2', 'Episode3', 'Episode4']
indices = [2, 0, 3, 1]
print(reorder_stack(stack1, indices))  
# Output: ['Episode2', 'Episode4', 'Episode1', 'Episode3']

stack2 = ['A', 'B', 'C', 'D']
indices = [1, 2, 3, 0]
print(reorder_stack(stack2, indices))  
# Output: ['D', 'A', 'B', 'C']

stack3 = ['Alpha', 'Beta', 'Gamma']
indices = [0, 2, 1]
print(reorder_stack(stack3, indices))  
# Output: ['Alpha', 'Gamma', 'Beta']
Fork me on GitHub