easy
1 views

Swap Even Integers Pair

Swap every pair of even integers in an array while keeping odd integers unchanged

Understand the Problem

Problem Statement

Problem Statement

The program must accept N integers as the input. The program swap every two even integers among the N integers. Then the program must print the N modified integers as the output. If the number of even integers is odd, the last even integer will remain the same as it has no pair to swap.

Constraints

Constraints

  • 2 ≤ N ≤ 1000
  • 1 ≤ Each integer value ≤ 10⁵

Examples

Example 1
Input
7
22 43 56 51 68 50 28
Output
56 43 22 51 50 68 28
Explanation

There are two even integer pairs in the given integers. The first even integer pair is 22 and 56. After swapping, the integers become 56 43 22 51 68 50 28. The second even integer pair is 68 and 50. After swapping, the integers become 56 43 22 51 50 68 28.

Example 2
Input
6
2 8 3 12 98 56
Output
8 2 3 98 12 56
Explanation

The even integer pairs are (2,8) and (12,98). After swapping: (8,2) and (98,12). The odd integer 3 remains unchanged.

Solution

#include <stdio.h>

int main() {
    int n;
    scanf("%d", &n);
    
    int arr[n];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    int count = 0;
    int firstEvenIndex = -1;
    
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 == 0) {
            count++;
            if (count == 2) {
                // Swap the pair
                int temp = arr[firstEvenIndex];
                arr[firstEvenIndex] = arr[i];
                arr[i] = temp;
                count = 0;
            }
            firstEvenIndex = i;
        }
    }
    
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}
Time:O(N) - We traverse the array exactly once
Space:O(N) - We store the input array, but O(1) additional space for variables
Approach:

Step-by-step explanation:

  1. Input Reading: Read N and then read N integers into an array
  2. Tracking Variables: Use count to track even integers in current pair (0, 1, or 2), and firstEvenIndex to store position of first even integer in pair
  3. Pair Detection: When encountering an even integer:
    • If it's the first even integer (count = 1), just store its index
    • If it's the second even integer (count = 2), swap it with the first even integer and reset count to 0
  4. Output: Print the modified array

The algorithm handles the case where there's an odd number of even integers naturally - the last even integer will have count = 1 but no second even integer to pair with, so it remains unchanged.

Visual Explanation

Loading diagram...