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.
1function swapSeats(students) {
2 for (let i = 0; i < students.length - 1; i += 2) {
3 [students[i], students[i + 1]] = [students[i + 1], students[i]];
4 }
5 return students;
6}
7
8let students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"];
9let result = swapSeats(students);
10result.forEach((student, index) => console.log(index + 1, student));
JavaScript uses destructuring assignment for swapping, simplifying the exchange of elements in an array. The code iterates through the student list, swapping pairs using a step of 2 in the loop.
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.
1
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.