Print the lexicographically smallest array by swapping elements whose sum is odd
Last Updated :
15 Dec, 2022
Given an array of N integers. The task is to find the lexicographically smallest array possible by applying the given operation any number of times. The operation is to pick two elements ai and aj (1<=i, j<=N) such that ai + aj is odd, and then swap ai and aj.
Examples:
Input : a[] = {1, 5, 4, 3, 2}
Output : 1 2 3 4 5
Explanation : First swap (5, 2) and then (4, 3). This is the
lexicographically smallest possible array that can be obtained by
swapping array elements satisfies given condition
Input : a[] = {4, 2}
Output : 4 2
Explanation : Not possible to swap any elements.
Approach: Observe that swapping of 2 elements is possible if they have different parity. If all elements in the array have the same parity (odd + odd and even + even is not odd), no swaps are possible. Hence the answer will be the input array only. Otherwise, you can actually swap any pair of elements. Assume you want to swap 2 elements, a and b, and they have the same parity. There must be a third element c that has a different parity. Without loss of generality, assume the array is [a, b, c]. Let’s do the following swaps:
- Swap a and c:
- Swap b and c: [b, c, a]
- Swap a and c: [b, a, c]
In other words, use c as an intermediate element to swap a and b, and it’ll always return to its original position afterward. Since swapping is possible between any pair of elements, we can always sort the array, which will be the lexicographically smallest array.
Below is the implementation of the above approach: