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.
1import java.util.ArrayList;
2import java.util.List;
3
4public class SeatSwap {
5 public static void main(String[] args) {
6 List<String> students = new ArrayList<>();
7 students.add("Abbot");
8 students.add("Doris");
9 students.add("Emerson");
10 students.add("Green");
11 students.add("Jeames");
12
13 swapSeats(students);
14
15 for (int i = 0; i < students.size(); i++) {
16 System.out.println((i + 1) + " " + students.get(i));
17 }
18 }
19
20 static void swapSeats(List<String> students) {
21 for (int i = 0; i < students.size() - 1; i += 2) {
22 String temp = students.get(i);
23 students.set(i, students.get(i + 1));
24 students.set(i + 1, temp);
25 }
26 }
27}
This Java implementation utilizes an ArrayList to dynamically manage the list of student names. The method swapSeats swaps every two adjacent names using a temporary variable for exchanging the indices. This demonstrates how Java's Collection framework can be leveraged for simple list manipulations.
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#
The C variant uses an extra 2D array to initially store swapped pairs, maintaining the original array intact. It later prints the new results by referencing the temporary storage after all swaps are completed.