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.
guests
of even length, containing both positive integers (attendees) and negative integers (absences).guests
list rearranged such that every consecutive pair of elements has opposite signs, starting with an attendee, while preserving the relative order of elements with the same sign.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Separate the list into attendees and absences, then alternate between them to construct the final list, ensuring that it starts with an attendee and that the order within each group is preserved.
1. Separate the `guests` list into two lists: one for attendees (positive integers) and one for absences (negative integers).
2. Initialize two pointers, `attendee_index` and `absence_index`, to iterate over the two lists.
3. Initialize an empty list `result` to store the rearranged guests.
4. While both `attendee_index` and `absence_index` are within the bounds of their respective lists:
1. Append an attendee to `result` from the `attendees` list.
2. Append an absence to `result` from the `absences` list.
3. Increment both pointers.
5. Return the `result` list, which now satisfies the conditions.
⚠️ Common Mistakes
def rearrange_guests(guests):
# Separate attendees and absences
attendees = [guest for guest in guests if guest > 0]
absences = [guest for guest in guests if guest < 0]
# Initialize pointers
attendee_index = 0
absence_index = 0
result = []
# Reconstruct the list alternating between attendees and absences
while attendee_index < len(attendees) and absence_index < len(absences):
result.append(attendees[attendee_index])
result.append(absences[absence_index])
attendee_index += 1
absence_index += 1
return result
# Example usage
print(rearrange_guests([3,1,-2,-5,2,-4])) # Output: [3,-2,1,-5,2,-4]
print(rearrange_guests([-1,1])) # Output: [1,-1]