Next same parity element in Circular Array
Given a circular array arr[] of size N, the task is to find the next integers of same parity for every element in arr[]. If the next integers with the same parity does not exist, return -1 for that number.
Examples:
Input: arr[] = {2, 4, 3, 6, 5}
Output: 4 6 5 2 3
Explanation: For 2 the next element with the same parity is 4.
For 4 the next element with the same parity is 6.
For 3 the next element with the same parity is 5.
For 6 the next element with the same parity is 2.
For 5 the next element with the same parity is 3.Input: arr[] = {5, 4, 7, 6}
Output: 7 6 5 4
Approach: The idea to solve the problem is as follows:
Iterate from the back of the array. If the arr[i] is odd, then it will act as the next odd element for any odd integer situated at j where j < i and j is closest to i. The same is true for the even elements also.
Follow the below steps to solve the problem:
- Initialize two variables to store the next odd(Next_Odd) and next even(Next_Even) for current array element.
- Iterate from i = 2*n-1 to 0:
- If i ≥ n, then the loop is usedd to find the next odd and even for the last odd and even element of the array.
- Otherwise, if arr[i] is odd and another odd element is present, put Next_Odd in resultant array and update Next_Odd to be arr[i].
- If arr[i] is even and another even element is present, put Next_Even in resultant array and update Next_Even to be arr[i].
- Return the resultant array.
Below is the implementation of the above approach:
C++
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to return next same parity// element in the arrayvector<int> findElement(int* arr, int n){ // Initialize the vector with -1 vector<int> SPE(n, -1); int Next_Even, Next_Odd; // To check if odd and even // are more than one or not int Count_Even = 0, Count_Odd = 0; for (int i = 2 * n - 1; i >= 0; i--) { // Duplicate array if (i >= n) { if (arr[i % n] & 1) { Next_Odd = arr[i % n]; Count_Odd++; } else { Next_Even = arr[i % n]; Count_Even++; } } // Original array else { if (arr[i] & 1) { if (Count_Odd > 1) { SPE[i] = Next_Odd; Next_Odd = arr[i]; } } else { if (Count_Even > 1) { SPE[i] = Next_Even; Next_Even = arr[i]; } } } } return SPE;} // Driver Codeint main(){ int arr[] = { 2, 4, 3, 6, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call vector<int> v = findElement(arr, N); for (auto i : v) { cout << i << " "; }} |
4 6 5 2 3
Time Complexity: O(N)
Auxiliary Space: O(1)


