Given an array arr[], rearrange its elements according to 1-based indexing such that for every even index i, arr[i] is greater than or equal to arr[i-1], and for every odd index i, arr[i] is less than or equal to arr[i-1]. Return the rearranged array that satisfies these conditions for all valid indices.
Find the resultant array.[consider 1-based indexing] .
Examples:
Input: arr[] = [1, 2, 2, 1]
Output: [1 2 1 2]
Explanation:
For i = 2, arr[i] >= arr[i-1]. So, 2 >= 1.
For i = 3, arr[i] <= arr[i-1]. So, 1 <= 2.
For i = 4, arr[i] >= arr[i-1]. So, 2 >= 1.Input: arr[] = [1, 3, 2]
Output: [1 3 2]
Explanation:
For i = 2,arr[i] >= arr[i-1]. So,3 >= 1.
For i = 3,arr[i] <= arr[i-1]. So,2 <= 3.
Table of Content
[Approach 1] - Assign Maximum Elements to Even Positions
Observe that array consists of [n/2] even positioned elements. If we assign the largest [n/2] elements to the even positions and the rest of the elements to the odd positions, our problem is solved. Because element at the odd position will always be less than the element at the even position as it is the maximum element and vice versa. Sort the array and assign the first [n/2] elements at even positions.
#include <vector>
#include <algorithm>
using namespace std;
vector<int> rearrangeArray(vector<int> &arr) {
int n = arr.size();
sort(arr.begin(), arr.end());
vector<int> ans(n);
int ptr1 = 0, ptr2 = n - 1;
for (int i = 0; i < n; i++) {
// Assign even indexes with maximum elements
if ((i + 1) % 2 == 0)
ans[i] = arr[ptr2--];
// Assign odd indexes with remaining elements
else
ans[i] = arr[ptr1++];
}
return ans;
}
int main() {
vector<int> arr = {1, 2, 2, 1};
vector<int> res = rearrangeArray(arr);
for (auto it : res)
cout << it << " ";
return 0;
}
import java.util.*;
public class GfG {
static ArrayList<Integer> rearrangeArray(ArrayList<Integer> arr) {
Collections.sort(arr);
int n = arr.size();
ArrayList<Integer> result = new ArrayList<>(Collections.nCopies(n, 0));
int ptr1 = 0, ptr2 = n - 1;
for (int i = 0; i < n; i++) {
// Assign even indexes (1-based) with maximum elements
if ((i + 1) % 2 == 0) {
result.set(i, arr.get(ptr2--));
}
// Assign odd indexes (1-based) with remaining elements
else {
result.set(i, arr.get(ptr1++));
}
}
return result;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(1, 2, 2, 1));
ArrayList<Integer> res = rearrangeArray(arr);
for (int num : res) {
System.out.print(num + " ");
}
}
}
def rearrangeArray(arr):
arr.sort()
n = len(arr)
result = [0] * n
ptr1, ptr2 = 0, n - 1
for i in range(n):
# Assign even indexes (1-based) with maximum elements
if (i + 1) % 2 == 0:
result[i] = arr[ptr2]
ptr2 -= 1
# Assign odd indexes (1-based) with remaining elements
else:
result[i] = arr[ptr1]
ptr1 += 1
return result
arr = [1, 2, 2, 1]
res = rearrangeArray(arr)
print(res)
using System;
using System.Collections.Generic;
class GfG {
static List<int> rearrangeArray(List<int> arr) {
arr.Sort();
int n = arr.Count;
List<int> result = new List<int>(new int[n]);
int ptr1 = 0, ptr2 = n - 1;
for (int i = 0; i < n; i++) {
// Assign even indexes (1-based) with maximum elements
if ((i + 1) % 2 == 0) {
result[i] = arr[ptr2--];
}
// Assign odd indexes (1-based) with remaining elements
else {
result[i] = arr[ptr1++];
}
}
return result;
}
public static void Main(string[] args) {
List<int> arr = new List<int> { 1, 2, 2, 1 };
List<int> res = rearrangeArray(arr);
foreach (int num in res) {
Console.Write(num + " ");
}
}
}
function rearrangeArray(arr) {
arr.sort((a, b) => a - b);
const n = arr.length;
const result = new Array(n).fill(0);
let ptr1 = 0, ptr2 = n - 1;
for (let i = 0; i < n; i++) {
// Assign even indexes (1-based) with maximum
// elements
if ((i + 1) % 2 === 0) {
result[i] = arr[ptr2--];
}
// Assign odd indexes (1-based) with remaining
// elements
else {
result[i] = arr[ptr1++];
}
}
return result;
}
const arr = [ 1, 2, 2, 1 ];
const res = rearrangeArray(arr);
console.log(res);
Output
1 2 1 2
Time Complexity: O(n * logn), where n is the size of input array .
Auxiliary Space: O(n)
[Approach 2] - Rearranging array by swapping elements
Traverse the array once from left to right and compare each element with its previous one. If a position is even (1-based) and the current element is smaller than the previous element, swap them. If a position is odd (1-based) and the current element is greater than the previous element, swap them. These local swaps ensure the array satisfies the given conditions in a single pass without extra space.
#include <iostream>
#include <vector>
using namespace std;
vector<int> rearrangeArray(vector<int> &arr) {
int n = arr.size();
vector<int> result(n);
// Traverse the array and make adjustments to satisfy the condition
for (int i = 1; i < n; i++) {
// Check if the index is even (1-based), i.e., i+1 is even
if ((i + 1) % 2 == 0) {
// Ensure that the current element is greater than or
// equal to the previous element
if (arr[i] < arr[i - 1]) {
swap(arr[i], arr[i - 1]);
}
}
else {
// Ensure that the current element is less than or equal
// to the previous element
if (arr[i] > arr[i - 1]) {
swap(arr[i], arr[i - 1]);
}
}
}
return arr;
}
int main() {
vector<int> arr = {1, 2, 2, 1};
int n = arr.size();
vector<int> res = rearrangeArray(arr);
for (int i = 0; i < n; i++) {
cout << res[i] << " ";
}
return 0;
}
import java.util.ArrayList;
import java.util.Collections;
class GfG {
static ArrayList<Integer>
rearrangeArray(ArrayList<Integer> arr) {
int n = arr.size();
// Traverse the array and make adjustments to
// satisfy the condition
for (int i = 1; i < n; i++) {
// Check if the index is even (1-based), i.e.,
// i+1 is even
if ((i + 1) % 2 == 0) {
// Ensure that the current element is
// greater than or equal to the previous
// element
if (arr.get(i) < arr.get(i - 1)) {
Collections.swap(arr, i, i - 1);
}
}
else {
// Ensure that the current element is less
// than or equal to the previous element
if (arr.get(i) > arr.get(i - 1)) {
Collections.swap(arr, i, i - 1);
}
}
}
return arr;
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<>();
arr.add(1);
arr.add(2);
arr.add(2);
arr.add(1);
ArrayList<Integer> res = rearrangeArray(arr);
for (int num : res) {
System.out.print(num + " ");
}
}
}
def rearrangeArray(arr):
n = len(arr)
# Traverse the array and make adjustments to satisfy the condition
for i in range(1, n):
# Check if the index is even (1-based), i.e., i+1 is even
if (i + 1) % 2 == 0:
# Ensure that the current element is greater than
# or equal to the previous element
if arr[i] < arr[i - 1]:
arr[i], arr[i - 1] = arr[i - 1], arr[i]
else:
# Ensure that the current element is less than or
# equal to the previous element
if arr[i] > arr[i - 1]:
arr[i], arr[i - 1] = arr[i - 1], arr[i]
return arr
if __name__ == "__main__":
inputArray = [1, 2, 2, 1]
resultArray = rearrangeArray(inputArray)
print(" ".join(map(str, resultArray)))
using System;
using System.Collections.Generic;
class GfG {
static List<int> RearrangeArray(List<int> arr) {
int n = arr.Count;
for (int i = 1; i < n; i++) {
// Check if the index is even (1-based), i.e.,
// i+1 is even
if ((i + 1) % 2 == 0) {
// Ensure that the current element is
// greater than or equal to the previous
// element
if (arr[i] < arr[i - 1]) {
int temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
else {
// Ensure that the current element is less
// than or equal to the previous element
if (arr[i] > arr[i - 1]) {
int temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
}
return arr;
}
static void Main() {
List<int> inputArray = new List<int>{ 1, 2, 2, 1 };
List<int> resultArray = RearrangeArray(inputArray);
foreach(var item in resultArray)
{
Console.Write(item + " ");
}
}
}
function rearrangeArray(arr) {
let n = arr.length;
// Traverse the array and make adjustments to satisfy
// the condition
for (let i = 1; i < n; i++) {
// Check if the index is even (1-based), i.e., i+1
// is even
if ((i + 1) % 2 === 0) {
// Ensure that the current element is greater
// than or equal to the previous element
if (arr[i] < arr[i - 1]) {
// Swap elements
[arr[i], arr[i - 1]] =
[ arr[i - 1], arr[i] ];
}
}
else {
// Ensure that the current element is less than
// or equal to the previous element
if (arr[i] > arr[i - 1]) {
// Swap elements
[arr[i], arr[i - 1]] =
[ arr[i - 1], arr[i] ];
}
}
}
return arr;
}
const inputArray = [ 1, 2, 2, 1 ];
const resultArray = rearrangeArray(inputArray);
console.log(resultArray.join(" "));
Output
1 2 1 2
Time Complexity: O(n), where n is the size of input array.
Auxiliary Space: O(1)