Given an array arr[], swap every ith element of the array with (i+2)th element.
Examples:
Input: arr[] = [1, 2, 3, 4, 5]
Output: [3, 4, 5, 2, 1]
Explanation: Swapping 1 and 3, makes the array 3 2 1 4 5. Now, swapping 2 and 4, makes the array 3 4 1 2 5.
Again, swapping 1 and 5, makes the array 3 4 5 2 1.Input: arr[] = [2, 4]
Output: [2, 4]
Explanation: There will be no swapping happen.
Table of Content
[Naive Approach] Extra Array - O(n) Time and O(n) Space
The idea is to first make a copy of the array and perform all the required swaps on this copy. Finally, copy the result back to the original array.
Working of Approach:
- Create an extra array temp as a copy of arr.
- Traverse the array from left to right.
- For every index i, swap temp[i] with temp[i + 2].
- Copy the modified temp back into arr.
- The final array contains all the required swaps.
#include <iostream>
#include <vector>
using namespace std;
// Function to swap elements in the array
void swapElements(vector<int> &arr)
{
int n = arr.size();
// Create an extra array
vector<int> temp = arr;
// Perform the required swaps
for (int i = 0; i + 2 < n; i++)
{
swap(temp[i], temp[i + 2]);
}
// Copy the result back to the original array
arr = temp;
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
swapElements(arr);
cout << "[";
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i];
if (i != arr.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
class GFG {
// Function to swap elements in the array
static void swapElements(int[] arr) {
int n = arr.length;
for (int i = 0; i + 2 < n; i++) {
int temp = arr[i];
arr[i] = arr[i + 2];
arr[i + 2] = temp;
}
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
swapElements(arr);
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i < arr.length - 1) {
System.out.print(", ");
}
}
System.out.print("]");
}
}
# Function to swap elements in the array
def swapElements(arr):
n = len(arr)
# Create an extra array
temp = arr.copy()
# Perform the required swaps
for i in range(n - 2):
temp[i], temp[i + 2] = temp[i + 2], temp[i]
# Copy the result back to the original array
for i in range(n):
arr[i] = temp[i]
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
swapElements(arr)
print('[', end='')
for i in range(len(arr)):
print(arr[i], end='' if i == len(arr) - 1 else ', ')
print(']')
using System;
class GFG {
// Function to swap elements in the array
public void swapElements(int[] arr)
{
int n = arr.Length;
// Create an extra array
int[] temp = (int[])arr.Clone();
// Perform the required swaps
for (int i = 0; i + 2 < n; i++) {
// Swap elements two positions apart
int t = temp[i];
temp[i] = temp[i + 2];
temp[i + 2] = t;
}
// Copy the result back to the original array
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
GFG obj = new GFG();
obj.swapElements(arr);
Console.Write("[");
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i]);
if (i != arr.Length - 1)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
// Function to swap elements in the array
function swapElements(arr)
{
let n = arr.length;
// Create an extra array
let temp = [...arr ];
// Perform the required swaps
for (let i = 0; i + 2 < n; i++) {
[temp[i], temp[i + 2]] = [ temp[i + 2], temp[i] ];
}
// Copy the result back to the original array
for (let i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
// Driver Code
let arr = [ 1, 2, 3, 4, 5 ];
swapElements(arr);
console.log(`[${arr.join(", ")}]`);
Output
[3, 4, 5, 2, 1]
[Expected Approach] In-Place Swapping - O(n) Time and O(1) Space
The idea is to perform each required swap directly in the given array. This avoids creating an extra array and completes the operation in a single traversal.
Working of Approach:
- Start traversing the array from index 0.
- For every index i, consider the element at i + 2.
- Swap arr[i] and arr[i + 2].
- Continue until i + 2 reaches the end of the array.
- Since the swaps are performed in-place, no extra space is required.
Let us understand with an example:
- Initially, arr = [1, 2, 3, 4, 5].
- For i = 0, swap arr[0] and arr[2] -> [3, 2, 1, 4, 5].
- For i = 1, swap arr[1] and arr[3] -> [3, 4, 1, 2, 5].
- For i = 2, swap arr[2] and arr[4] -> [3, 4, 5, 2, 1].
- The loop ends, so the final array is [3, 4, 5, 2, 1].
#include <iostream>
#include <vector>
using namespace std;
// Function to swap elements in the array
void swapElements(vector<int> &arr)
{
int n = arr.size();
for (int i = 0; i < n - 2; i++)
{
// Swap elements two positions apart
swap(arr[i], arr[i + 2]);
}
}
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
swapElements(arr);
cout << "[";
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i];
if (i != arr.size() - 1)
cout << ", ";
}
cout << "]";
return 0;
}
class GFG {
// Function to swap elements in the array
static void swapElements(int[] arr)
{
int n = arr.length;
for (int i = 0; i < n - 2; i++) {
// Swap elements two positions apart
int temp = arr[i];
arr[i] = arr[i + 2];
arr[i + 2] = temp;
}
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
swapElements(arr);
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i != arr.length - 1)
System.out.print(", ");
}
System.out.print("]");
}
}
def swapElements(arr):
n = len(arr)
for i in range(n - 2):
# Swap elements two positions apart
arr[i], arr[i + 2] = arr[i + 2], arr[i]
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5]
swapElements(arr)
print('[', end='')
for i in range(len(arr)):
print(arr[i], end='' if i == len(arr) - 1 else ', ')
print(']')
using System;
class GFG {
// Function to swap elements in the array
static void swapElements(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 2; i++) {
// Swap elements two positions apart
int temp = arr[i];
arr[i] = arr[i + 2];
arr[i + 2] = temp;
}
}
static void Main()
{
int[] arr = { 1, 2, 3, 4, 5 };
swapElements(arr);
Console.Write("[");
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i]);
if (i != arr.Length - 1)
Console.Write(", ");
}
Console.Write("]");
}
}
function swapElements(arr)
{
let n = arr.length;
for (let i = 0; i < n - 2; i++) {
// Swap elements two positions apart
let temp = arr[i];
arr[i] = arr[i + 2];
arr[i + 2] = temp;
}
}
// Driver Code
let arr = [ 1, 2, 3, 4, 5 ];
swapElements(arr);
console.log("[" + arr.join(", ") + "]");
Output
[3, 4, 5, 2, 1]