![]() |
VOOZH | about |
Given an array arr[], the task is to rearrange the array elements by swapping adjacent elements such that no element remains at the same position after swapping.
Examples:
Input: arr[] = { 1, 2, 3, 4, 5 }
Output: 2 1 5 3 4
Explanation:
Adjacent elements are swapped as follows:
(1, 2 -> 2, 1)
(3, 4, 5 -> 5, 3, 4)
Input: arr[] = {1, 2, 3, 4}
Output: 2 1 4 3
Explanation:
Adjacent elements are swapped as follows:
1, 2 -> 2, 1
3, 4 -> 4, 3
Approach: The key observation in the problem is that there can be two cases for the arrays to swap the array elements:
Below is the implementation of the above approach:
2 1 4 5 3
Time Complexity: O(N)
Auxiliary Space: O(1)