The Wayback Machine - https://web.archive.org/web/20240818163938/https://www.geeksforgeeks.org/rearrange-array-maximum-minimum-form/
Open In App

Rearrange an array in maximum minimum form using Two Pointer Technique

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. 

Examples: 

Input: arr[] = {1, 2, 3, 4, 5, 6, 7} 
Output: arr[] = {7, 1, 6, 2, 5, 3, 4}
Explanation: First 7 is the max value, then 1 is the min value, then 6 is the second max value, then 2 is the second min value, then 5 is the third max value, then 3 is the third min value and at last 4 is the fourth max value.

Input: arr[] = {1, 2, 3, 4, 5, 6} 
Output: arr[] = {6, 1, 5, 2, 4, 3} 

Rearrange an array in maximum minimum form using Two Pointers:

The idea is to use an auxiliary array. We maintain two pointers one to the leftmost or smallest element and the other to the rightmost or largest element. We move both pointers toward each other and alternatively copy elements at these pointers to an auxiliary array. Finally, we copy the auxiliary array back to the original array.

Below is the implementation of the above approach:

C++
// C++ program to rearrange an array in minimum
// maximum form
#include <bits/stdc++.h>
using namespace std;

// function to rearrange the array elements alternately
void rearrange(long long* arr, int n)
{
    // Auxiliary array to hold modified array
    long long temp[n];

    // Indexes of smallest and largest elements
    // from remaining array.
    int small = 0, large = n - 1;

    // To indicate whether we need to copy remaining
    // largest or remaining smallest at next position
    int flag = true;

    // Store result in temp[]
    for (int i = 0; i < n; i++) {
        if (flag)
            temp[i] = arr[large--];
        else
            temp[i] = arr[small++];

        flag = !flag;
    }

    // Copy temp[] to arr[]
    for (int i = 0; i < n; i++)
        arr[i] = temp[i];
}

// Driver code
int main()
{
    long long arr[] = { 1, 2, 3, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Original Array\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";

    rearrange(arr, n);

    cout << "\nModified Array\n";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    return 0;
}
Java
// Java program to rearrange an array in minimum
// maximum form
import java.util.Arrays;

public class MinMaxRearrange {
    // function to rearrange the array elements alternately
    static void rearrange(long[] arr, int n)
    {
        // Auxiliary array to hold modified array
        long[] temp = new long[n];

        // Indexes of smallest and largest elements
        // from remaining array.
        int small = 0, large = n - 1;

        // To indicate whether we need to copy remaining
        // largest or remaining smallest at next position
        boolean flag = true;

        // Store result in temp[]
        for (int i = 0; i < n; i++) {
            if (flag) {
                temp[i] = arr[large--];
            }
            else {
                temp[i] = arr[small++];
            }
            flag = !flag;
        }

        // Copy temp[] to arr[]
        for (int i = 0; i < n; i++)
            arr[i] = temp[i];
    }

    // Driver code
    public static void main(String[] args)
    {
        long[] arr = { 1, 2, 3, 4, 5, 6 };
        int n = arr.length;

        System.out.println("Original Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
      
        rearrange(arr, n);

        System.out.println("\nModified Array");
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
}
Python
# Python program to rearrange an array in minimum
# maximum form

# Function to rearrange the array elements alternately
def rearrange(arr):
    n = len(arr)
    temp = [0] * n

    # Indexes of smallest and largest elements
    small, large = 0, n - 1

    # To indicate whether we need to copy remaining
    # largest or remaining smallest at next position
    flag = True

    # Store result in temp[]
    for i in range(n):
        if flag:
            temp[i] = arr[large]
            large -= 1
        else:
            temp[i] = arr[small]
            small += 1
        flag = not flag

    # Copy temp[] to arr[]
    for i in range(n):
        arr[i] = temp[i]


# Driver code
arr = [1, 2, 3, 4, 5, 6]
n = len(arr)

print("Original Array")
for x in arr:
    print(x, end=" ")

rearrange(arr)

print("\nModified Array")
for x in arr:
    print(x, end=" ")
C#
// C# program to rearrange an array in minimum maximum form
using System;

class GFG
{
    // Function to rearrange the array elements alternately
    static void Rearrange(long[] arr, int n)
    {
        // Auxiliary array to hold modified array
        long[] temp = new long[n];

        // Indexes of smallest and largest elements
        // from remaining array.
        int small = 0, large = n - 1;

        // To indicate whether we need to copy remaining
        // largest or remaining smallest at next position
        bool flag = true;

        // Store result in temp[]
        for (int i = 0; i < n; i++)
        {
            if (flag)
                temp[i] = arr[large--];
            else
                temp[i] = arr[small++];

            flag = !flag;
        }

        // Copy temp[] to arr[]
        for (int i = 0; i < n; i++)
            arr[i] = temp[i];
    }

    // Driver code
    static void Main()
    {
        long[] arr = { 1, 2, 3, 4, 5, 6 };
        int n = arr.Length;

        Console.WriteLine("Original Array");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");

        Rearrange(arr, n);

        Console.WriteLine("\nModified Array");
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
}
JavaScript
// JavaScript program to rearrange an array in minimum
// maximum form

// Function to rearrange the array elements alternately
function rearrange(arr) {
    // Auxiliary array to hold modified array
    let temp = new Array(arr.length);

    // Indexes of smallest and largest elements
    // from remaining array.
    let small = 0, large = arr.length - 1;

    // To indicate whether we need to copy remaining
    // largest or remaining smallest at next position
    let flag = true;

    // Store result in temp[]
    for (let i = 0; i < arr.length; i++) {
        if (flag)
            temp[i] = arr[large--];
        else
            temp[i] = arr[small++];

        flag = !flag;
    }

    // Copy temp[] to arr[]
    for (let i = 0; i < arr.length; i++)
        arr[i] = temp[i];
}

// Driver code
let arr = [1, 2, 3, 4, 5, 6];

console.log("Original Array");
for (let i = 0; i < arr.length; i++)
    console.log(arr[i] + " ");

rearrange(arr);

console.log("\nModified Array");
for (let i = 0; i < arr.length; i++)
    console.log(arr[i] + " ");

Output
Original Array
1 2 3 4 5 6 
Modified Array
6 1 5 2 4 3 

Working:

Below is the working of how to rearrange an array in maximum minimum form using Two Pointer Technique:


Complexity Analysis:

  • Time Complexity: O(N), Iterating over the array of size N 2 times.
  • Auxiliary Space: O(N), since N extra space has been taken.

Exercise: How to solve this problem if extra space is not allowed? 
Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)



Previous Article
Next Article

Similar Reads

Two-Pointer Technique in a Linked List
The two-pointer technique is a common technique used in linked list problems to solve a variety of problems efficiently. It involves using two pointers that traverse the linked list at different speeds or in different directions. Use Cases of Two-Pointer Technique in a Linked List:1. Finding the Middle of a Linked List:One common application of the
3 min read
Rearrange an array in maximum minimum form in O(1) extra space
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be the maximum value, second minimum value, third-second max, fourth-second min and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2, 5, 3, 4}Explanation: First 7 is the max value, then 1 is the min value, then 6 is t
9 min read
How to create a pointer to another pointer in a linked list?
In this article we cover how to create a pointer to another pointer in a linked list, it can be singly, doubly, or circularly. What is Linked List: A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Singly
7 min read
Rearrange array to make it non-decreasing by swapping pairs having GCD equal to minimum array element
Given an array, arr[] consisting of N positive integers, the task is to make the array non-decreasing by swapping pairs (arr[i], arr[j]) such that i != j (1 ≤ i, j ≤ n) and GCD(arr[i], arr[j]) is equal to the minimum element present in the array. Examples: Input: arr[] = {4, 3, 6, 6, 2, 9}Output: YesExplanation: Minimum array element = 2. Swap arr[
6 min read
Minimum cost required to rearrange a given array to make it equal to another given array
Given two arrays A[] and B[] consisting of M and N integers respectively, and an integer C, the task is to find the minimum cost required to make the sequence A exactly the same as B(consists of distinct elements only) by performing the following operations on array A[]: Remove any element from the array with cost 0.Insert a new element anywhere in
12 min read
Rearrange a given list such that it consists of alternating minimum maximum elements
Given a list of integers, rearrange the list such that it consists of alternating minimum maximum elements using only list operations. The first element of the list should be minimum and second element should be maximum of all elements present in the list. Similarly, third element will be next minimum element and fourth element is next maximum elem
9 min read
Python3 Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive solution. C/C++ Code # Naive solution to find if the
3 min read
Javascript Program for Two Pointers Technique
Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Let’s see the naive solution.   C/C++ Code &lt;script&gt; // Naive solut
4 min read
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Illustration : A[] = {10, 20, 35, 50, 75, 80}X = =70i = 0j = 5A[i] + A[j]
13 min read
Rearrange array to obtain maximum possible value of concatenation of prefix GCDs
Given an array arr[] consisting of N positive integers, the task is to rearrange the array elements such that the number formed by concatenating the GCD of elements of the array arr[] from index 0 to i for each index i is the maximum possible. Examples: Input: arr[] = {4, 2, 5}Output: 5 4 2Explanation:X = 511 is the maximum value of X that can be o
9 min read
Minimum steps required to rearrange given array to a power sequence of 2
Given an array arr[] consisting of N positive integers, the task is to find the minimum steps required to make the given array of integers into a sequence of powers of 2 by the following operations: Reorder the given array. It doesn't count as a step.For each step, select any index i from the array and change arr[i] to arr[i] ? 1 or arr[i] + 1. A s
4 min read
Rearrange Array such that sum of adjacent sum divided by K is minimum
Given an integer array arr[] of length N and an integer K, the task is to rearrange the elements of arr[] in such a way that the value of the total sum of Ai + Ai + 1 divided by K is minimized for all (1 ≤ i ≤ N - 1). If there are multiple arrangements, then print any of them. Examples: Input: N = 5, arr[] = {4, 7, 1}, K = 3Output: arr[] = {7, 1, 4
6 min read
Rearrange an array such that product of every two consecutive elements is a multiple of 4
Given an array arr[] of size N, the task is to rearrange the array elements such that for every index i(1 &lt;= i &lt;= N - 1), the product of arr[i] and arr[i - 1] is a multiple of 4.Example: Input: arr[] = {1, 10, 100} Output: 1, 100, 10 Explanation: 1 * 100 is divisible by 4 100 * 10 is divisible by 4 Input: arr[] = {2, 7, 1, 8, 2, 8} Output: 7,
11 min read
Partition array into two subsets with minimum Bitwise XOR between their maximum and minimum
Given an array arr[] of size N, the task is to split the array into two subsets such that the Bitwise XOR between the maximum of the first subset and minimum of the second subset is minimum. Examples: Input: arr[] = {3, 1, 2, 6, 4} Output: 1 Explanation: Splitting the given array in two subsets {1, 3}, {2, 4, 6}. The maximum of the first subset is
5 min read
Rearrange characters in a string such that no two adjacent are same using hashing
Given a string str with repeated characters, the task is to rearrange the characters in a string such that no two adjacent characters are the same. If it is possible then print Yes else print No. Examples: Input: str = "geeksforgeeks" Output: Yes "egeksforegeks" is one such arrangement. Input: str = "bbbbb" Output: No Approach: The idea is to store
5 min read
Rearrange characters to form palindrome if possible
Given a string, convert the string to palindrome without any modifications like adding a character, removing a character, replacing a character etc. Examples: Input : "mdaam" Output : "madam" or "amdma" Input : "abb" Output : "bab" Input : "geeksforgeeks" Output : "No Palindrome"Count occurrences of all characters. Count odd occurrences. If this co
7 min read
Rearrange a string in the form of integer sum followed by the minimized character
Given a string including lowercase alphabets and numeric digits. The task is to construct another string which consists of the sum of digits followed by the sum of all alphabets minimized to a single character. If no numeric digit is present add 0 to the string. Note: Alphabet summation is done in this manner: a+a = b, d+y = c. Examples: Input: str
5 min read
LCA in a tree using Binary Lifting Technique
Given a binary tree, the task is to find the Lowest Common Ancestor of the given two nodes in the tree. Let G be a tree then the LCA of two nodes u and v is defined as the node w in the tree which is an ancestor of both u and v and is farthest from the root node. If one node is the ancestor of another one then that particular node is the LCA of tho
14 min read
Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
Given a vertex V of an N-ary tree and an integer K, the task is to print the Kth ancestor of the given vertex in the tree. If there does not exist any such ancestor then print -1.Examples: Input: K = 2, V = 4 Output: 1 2nd parent of vertex 4 is 1.Input: K = 3, V = 4 Output: -1 Approach: The idea is to use Binary Lifting Technique. This technique is
9 min read
Sum of length of paths from every node to all other nodes using Tree Rerooting technique
For every node in an undirected tree, find the sum of length of paths from it to all other nodes, using Tree Rerooting technique. Rerooting is a dynamic programming technique in trees. Using this a property dp[i] on tree is calculated, when the tree is rooted at i. Example: Input: Consider the tree shown in the image: Output: 12 9 17 14 10 15 15 Ex
15+ min read
Maximum index a pointer can reach in N steps by avoiding a given index B - Set 3 (Binary Search)
Given two integers N and B, the task is to print the maximum index a pointer, starting from 0th index can reach in an array of natural numbers(i.e., 0, 1, 2, 3, 4, 5…), say arr[], in N steps without placing itself at index B at any point. In each step, the pointer can move from the Current Index to a Jumping Index or can remain at the Current Index
7 min read
Maximum index a pointer can reach in N steps by avoiding a given index B | Set 2
Given two integers N and B, the task is to print the maximum index in an array that can be reached, starting from the 0th index, in N steps without placing itself at index B at any point, where in every ith step, pointer can move i indices to the right. Examples: Input: N = 4, B = 6Output: 9Explanation: Following sequence of moves maximizes the ind
10 min read
Rearrange the array to maximize the number of primes in prefix sum of the array
Given an array arr[] of 1's and 2's, the task is to re-arrange the array in such a way that the prefix sum of the rearranged array has the maximum number of primes. Note that there can be multiple answers to it. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 2 1 1 1 2 The prefix sum array is {2, 3, 4, 5, 7} which has {2, 3, 5, 7} as primes which
9 min read
Rearrange an Array such that Sum of same-indexed subsets differ from their Sum in the original Array
Given an array A[] consisting of N distinct integers, the task is to rearrange the given array such that the sum of every same-indexed non-empty subsets of size less than N, is not equal to their sum in the original array.Examples: Input: A[] = {1000, 100, 10, 1} Output: 100 10 1 1000 Explanation: Original Array A[] = {1000, 100, 10, 1} Final Array
6 min read
Rearrange array such that all even-indexed elements in the Array is even
Given an array arr[], the task is to check if it is possible to rearrange the array in such a way that every even index(1-based indexing) contains an even number. If such a rearrangement is not possible, print "No". Otherwise, print "Yes" and print a possible arrangement Examples: Input: arr[] = {2, 4, 8, 3, 1} Output: Yes 3 4 8 2 1Input: arr[] = {
6 min read
Rearrange Array to maximize number having Array elements as digits based on given conditions
Given an array of integers arr[] and a binary string str of length N, the task is to rearrange given array by swapping array elements from indices having the same character in the string, such that the number formed by the elements of the rearranged array as digits is the maximum possible. Examples: Input: arr[]={1, 3, 4, 2}, str=”0101” Output: 4 3
7 min read
Rearrange an array to make similar indexed elements different from that of another array
Given two sorted arrays A[] and B[] consisting of N distinct integers, the task is to rearrange the elements of array B[] such that, for every ith index, A[i] is not equal to B[i]. If multiple such arrangements exist, print any one of them. If no such arrangement exists, print -1. Examples: Input: A[] = {2, 4, 5, 8}, B[] = {2, 4, 5, 8}Output: 4 2 8
7 min read
Rearrange array by interchanging positions of even and odd elements in the given array
Given an array arr[] of N positive integers with an equal number of even and odd elements. The task is to use in-place swapping to interchange positions of even and odd elements in the array. Examples: Input: arr[] = {1, 3, 2, 4}Output: 2 4 1 3Explanation:Before rearranging the given array, indices 0 and 1 had odd elements and indices 2 and 3 had e
15+ min read
Rearrange array to make product of prefix sum array non zero
Given an array, arr[ ] of size N, the task is to rearrange the given array such that the product of all the elements of its prefix sum array is not equal to 0. If it is not possible to rearrange the array that satisfies the given condition, then print -1. Examples: Input: arr[] = {1, -1, -2, 3}Output: 3 1 -1 -2Explanation:Prefix sum after rearrangi
7 min read
Rearrange array to maximize sum of GCD of array elements with their respective indices
Given an array arr[] consisting of a permutation of first N natural numbers, the task is to find the maximum possible value of ?GCD(arr[i], i) (1-based indexing) by rearranging the given array elements. Examples: Input: arr[] = { 2, 1} Output: 6 Explanation: Rearranging the given array to { 2, 1}. ?GCD(arr[i], i) = GCD(arr[1], 1) + GCD(arr[2], 2) =
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg