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.
stack
) and a list of indices (indices
) representing the new order.indices
list is unique and valid.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.
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']