easy
0 views

Outer to Inner Swap – Both Odd/Even

Swap elements from outer positions to inner positions if both elements are odd or both are even

Understand the Problem

Problem Statement

Given N numbers, the program must swap the first and last element, swap 2nd and last but one element and so on if both the elements are odd or even. If N is odd, the swap will not occur for the middle element.

Constraints

  • 2 ≤ N ≤ 9999
  • Value of a given number is from 1 to 99999
  • Array elements must be positive integers
  • Only swap if both elements have same parity (both odd or both even)

Examples

Example 1
Input
7
4 11 17 6 11 18 2
Output
2 11 11 6 17 18 4
Explanation

Take 4 and 2. Swap occurs as both are even. Now 11 and 18, no swap as 11 is odd and 18 is even. Now consider the pair 17 and 11. Swap occurs as both are odd. 6 is middle element (as N is odd) and hence retained as it is.

Example 2
Input
4
2 4 6 8
Output
8 6 4 2
Explanation

All elements are even, so all pairs will be swapped: 2↔8 and 4↔6

Example 3
Input
6
1 3 5 7 9 11
Output
11 9 7 5 3 1
Explanation

All elements are odd, so all pairs will be swapped: 1↔11, 3↔9, and 5↔7

Solution

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    scanf("%d", &n);
    int a[n];
    int i, j = 0, k = n - 1, temp;
    
    // Read input array
    for (i = 0; i < n; i++)
        scanf("%d", &a[i]);
    
    // Swap elements from outer to inner if both have same parity
    for (i = 0; i < n / 2; i++)
    {
        if ((a[k] % 2 == 0 && a[j] % 2 == 0) || (a[k] % 2 != 0 && a[j] % 2 != 0))
        {
            // Swap elements
            temp = a[k];
            a[k] = a[j];
            a[j] = temp;
        }
        k--;
        j++;
    }
    
    // Print the result
    for (i = 0; i < n; i++)
        printf("%d ", a[i]);
    
    return 0;
}
Time:O(N) - We iterate through half the array once
Space:O(1) - We use only a constant amount of extra space for variables
Approach:

Step-by-step explanation:

  1. Read the number of elements N
  2. Declare and read the array of size N
  3. Initialize two pointers: j=0 (start) and k=n-1 (end)
  4. Loop through the first half of the array (i < n/2)
  5. For each pair, check if both elements have same parity using modulo operator
  6. If both are even (a[k]%2==0 && a[j]%2==0) OR both are odd (a[k]%2!=0 && a[j]%2!=0), swap them
  7. Move pointers: increment j, decrement k
  8. After loop, print the modified array

The middle element (if N is odd) is automatically left untouched since we only iterate through n/2 positions.

Visual Explanation

Loading diagram...