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 fabric rolls be organized?
Q: What should the function return if there is an odd number of fabric rolls?
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Sort the fabric rolls by their length, then pair them sequentially to minimize the difference in lengths. If there's an odd number of rolls, the last roll remains unpaired.
1) Sort the `fabric_rolls` list in ascending order.
2) Initialize an empty list called `pairs`.
3) While the length of `fabric_rolls` is greater than 1:
a) Pop the smallest element (first in the sorted list) and the next smallest element.
b) Append these two elements as a tuple to the `pairs` list.
4) If there is one fabric roll left unpaired, append it to the `pairs` list as a single element.
5) Return the `pairs` list.
**⚠️ Common Mistakes**
- Forgetting to handle the case where there is an odd number of rolls, leaving one unpaired.
- Not correctly sorting the rolls, which can lead to suboptimal pairing.
def organize_fabric_rolls(fabric_rolls):
fabric_rolls.sort() # Sort the fabric rolls by length
pairs = []
while len(fabric_rolls) > 1:
smallest = fabric_rolls.pop(0)
closest = fabric_rolls.pop(0)
pairs.append((smallest, closest))
if fabric_rolls:
return pairs + [fabric_rolls[0]]
else:
return pairs