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.
1#include <iostream>
2#include <vector>
3#include <string>
4
5void swapSeats(std::vector<std::string> &students) {
6 for (size_t i = 0; i < students.size() - 1; i += 2) {
7 std::swap(students[i], students[i + 1]);
8 }
9}
10
11int main() {
12 std::vector<std::string> students = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
13 swapSeats(students);
14 for (size_t i = 0; i < students.size(); ++i) {
15 std::cout << i + 1 << " " << students[i] << std::endl;
16 }
17 return 0;
18}
The C++ solution uses a vector to store the student names. A simple for loop with a step of 2 swaps adjacent elements using the built-in swap function. This efficiently exchanges seats by leveraging in-place swaps.
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
By using array spread syntax, JavaScript efficiently duplicates the original array before modifying it. This supports the principle of keeping original records intact by conducting operations on a separate data structure.