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?
Q: What is the output?
Q: How should the fabrics be organized?
Q: Are there any constraints on the input, such as the fabrics needing to be sorted?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Sort the fabrics by their eco-friendliness rating, then push the fabric names onto a stack. Finally, pop the fabrics from the stack to retrieve them in the desired order.
1) Sort the `fabrics` list by the eco-friendliness rating in ascending order.
2) Initialize an empty list called `stack`.
3) For each `fabric` in `fabrics`:
a) Push the `fabric[0]` (fabric name) onto the `stack`.
4) Initialize an empty list called `organized_fabrics`.
5) While the `stack` is not empty:
a) Pop the top element from `stack` and append it to `organized_fabrics`.
6) Return the `organized_fabrics` list.
**⚠️ Common Mistakes**
- Forgetting to correctly sort the fabrics by their eco-friendliness rating.
- Not correctly implementing the stack operations (push and pop).
def organize_fabrics(fabrics):
fabrics.sort(key=lambda x: x[1]) # Sort fabrics by eco-friendliness rating
stack = []
for fabric in fabrics:
stack.append(fabric[0]) # Push fabric names onto the stack
organized_fabrics = []
while stack:
organized_fabrics.append(stack.pop()) # Pop fabrics from the stack in reverse order
return organized_fabrics