Sponsored
Sponsored
This approach involves iterating through the list and swapping every two consecutive students. The loop runs with a step of 2 to handle even-indexed pairs, ensuring that swaps are done pair-wise. If the total number of students is odd, the last student remains in their original position as there is no pair to swap with.
Time Complexity: O(n), since each element may be swapped once.
Space Complexity: O(1), as no extra space is used except the temporary variable for swapping.
1def swap_seats(students):
2 for i in range(0, len(students) - 1, 2):
3 students[i], students[i + 1] = students[i + 1], students[i]
4 return students
5
6students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"]
7result = swap_seats(students)
8for i, student in enumerate(result, 1):
9 print(i, student)
In Python, lists (which are mutable) are utilized to store students’ names. The swap occurs using tuple unpacking, a simple way to efficiently exchange the two elements at adjacent positions.
This method employs a temporary array or list to store swapped results before copying them back to the original list or directly returning them as new results. This makes the logic conceptually simpler at the cost of some additional space usage.
Time Complexity: O(n) due to linear traversal.
Space Complexity: O(n), using a full-sized temporary array.
1import
In this Java solution, an ArrayList is cloned initially, followed by in-place swaps in the cloned list. Final output retrieves data without altering the original student list.