TIP102 Unit 3 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.
attendees
where each element represents the priority level of an attendee, and an integer priority
that indicates a particular level of priority.attendees
list rearranged such that attendees with lower priority appear first, followed by those with the exact priority, and finally those with higher priority, while preserving the relative order within each group.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a three-way partitioning approach similar to the Dutch National Flag problem to rearrange the attendees
list according to the specified priority while maintaining the relative order within each group.
1. Initialize three pointers:
* `left` to track the end of the less-than-priority group.
* `right` to track the start of the greater-than-priority group.
* `i` to iterate through the list.
2. Iterate through the `attendees` list using `i`:
1. If the current attendee's priority is less than the specified priority:
* Swap it with the element at `left`.
* Increment both `left` and `i`.
2. If the current attendee's priority is greater than the specified priority:
* Swap it with the element at `right`.
* Decrement `right`.
3. If the current attendee's priority is equal to the specified priority:
* Just increment `i`.
3. Continue this process until `i` passes `right`.
4. Return the modified `attendees` list.
⚠️ Common Mistakes
def arrange_attendees_by_priority(attendees, priority):
left = 0
right = len(attendees) - 1
i = 0
while i <= right:
if attendees[i] < priority:
attendees[left], attendees[i] = attendees[i], attendees[left]
left += 1
i += 1
elif attendees[i] > priority:
attendees[right], attendees[i] = attendees[i], attendees[right]
right -= 1
else:
i += 1
return attendees
# Example usage
print(arrange_attendees_by_priority([9,12,5,10,14,3,10], 10)) # Output: [9,5,3,10,10,12,14]
print(arrange_attendees_by_priority([-3,4,3,2], 2)) # Output: [-3,2,4,3]