Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements

Given an array of N integers, the task is to arrange them in a circular arrangement in such a way that the element is strictly less than the sum of its adjacent elements. In case such an arrangement is not possible, then print -1.Â
Note that there can be multiple ways of arranging the elements such that the condition is satisfied and the task is to find any such arrangement.
Examples:Â
Â
Input: arr[] = {1, 4, 4, 3, 2}Â
Output: 1 3 4 4 2Â
arr[0] = 1 < (2 + 4)Â
arr[1] = 4 < (1 + 4)Â
arr[2] = 4 < (4 + 3)Â
arr[3] = 3 < (4 + 2)Â
arr[4] = 2 < (3 + 1)
Input: arr[] = {8, 13, 5}Â
Output: -1Â
Â
Â
Approach: The problem can be solved using a greedy approach, we first sort the array and then place the smallest element at the beginning, the second smallest at the end, the third smallest at the second position and the fourth smallest at the second last position in another array. Once the arrangement is completed, check if the given condition is satisfied or not.
Below is the implementation of the above approach:Â
Â
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the arrangement that// satisfies the given conditionvoid printArrangement(int a[], int n){Â
    // Sort the array initially    sort(a, a + n);Â
    // Array that stores the arrangement    int b[n];Â
    // Once the array is sorted    // Re-fill the array again in the    // mentioned way in the approach    int low = 0, high = n - 1;    for (int i = 0; i < n; i++) {        if (i % 2 == 0)            b[low++] = a[i];        else            b[high--] = a[i];    }Â
    // Iterate in the array    // and check if the arrangement made    // satisfies the given condition or not    for (int i = 0; i < n; i++) {Â
        // For the first element        // the adjacents will be a[1] and a[n-1]        if (i == 0) {            if (b[n - 1] + b[1] <= b[i]) {                cout << -1;                return;            }        }Â
        // For the last element        // the adjacents will be a[0] and a[n-2]        else if (i == (n - 1)) {            if (b[n - 2] + b[0] <= b[i]) {                cout << -1;                return;            }        }        else {            if (b[i - 1] + b[i + 1] <= b[i]) {                cout << -1;                return;            }        }    }Â
    // If we reach this position then    // the arrangement is possible    for (int i = 0; i < n; i++)        cout << b[i] << " ";}Â
// Driver codeint main(){Â Â Â Â int a[] = { 1, 4, 4, 3, 2 };Â Â Â Â int n = sizeof(a) / sizeof(a[0]);Â
    printArrangement(a, n);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.Arrays;Â
class GFG {Â
// Function to print the arrangement that// satisfies the given conditionstatic void printArrangement(int a[], int n){Â
    // Sort the array initially    Arrays.sort(a);Â
    // Array that stores the arrangement    int b[] = new int[n];Â
    // Once the array is sorted    // Re-fill the array again in the    // mentioned way in the approach    int low = 0, high = n - 1;    for (int i = 0; i < n; i++)     {        if (i % 2 == 0)            b[low++] = a[i];        else            b[high--] = a[i];    }Â
    // Iterate in the array    // and check if the arrangement made    // satisfies the given condition or not    for (int i = 0; i < n; i++)    {Â
        // For the first element        // the adjacents will be a[1] and a[n-1]        if (i == 0)        {            if (b[n - 1] + b[1] <= b[i])            {                System.out.print(-1);                return;            }        }Â
        // For the last element        // the adjacents will be a[0] and a[n-2]        else if (i == (n - 1))         {            if (b[n - 2] + b[0] <= b[i])            {                System.out.print(-1);                return;            }        }        else        {            if (b[i - 1] + b[i + 1] <= b[i])            {                System.out.print(-1);                return;            }        }    }Â
    // If we reach this position then    // the arrangement is possible    for (int i = 0; i < n; i++)        System.out.print(b[i] + " ");}Â
// Driver codepublic static void main (String[] args) {Â Â Â Â int a[] = { 1, 4, 4, 3, 2 };Â Â Â Â int n = a.length;Â
    printArrangement(a, n);}}Â
// This code is contributed by anuj_67.. |
Python3
# Python3 implementation of the approachÂ
# Function to print the arrangement that# satisfies the given conditiondef printArrangement(a, n):Â
    # Sort the array initially    a = sorted(a)Â
    # Array that stores the arrangement    b = [0 for i in range(n)]Â
    # Once the array is sorted    # Re-fill the array again in the    # mentioned way in the approach    low = 0    high = n - 1    for i in range(n):        if (i % 2 == 0):            b[low] = a[i]            low += 1        else:            b[high] = a[i]            high -= 1Â
    # Iterate in the array    # and check if the arrangement made    # satisfies the given condition or not    for i in range(n):Â
        # For the first element        # the adjacents will be a[1] and a[n-1]        if (i == 0):            if (b[n - 1] + b[1] <= b[i]):                print("-1")                return                         # For the last element        # the adjacents will be a[0] and a[n-2]        elif (i == (n - 1)) :            if (b[n - 2] + b[0] <= b[i]):                print("-1")                returnÂ
        else:            if (b[i - 1] + b[i + 1] <= b[i]):                print("-1")                returnÂ
    # If we reach this position then    # the arrangement is possible    for i in range(n):        print(b[i], end = " ")Â
# Driver codea = [ 1, 4, 4, 3, 2 ]n = len(a)Â
printArrangement(a, n)Â
# This code is contributed by Mohit Kumar |
C#
// C# implementation of the approachusing System;Â
class GFG {Â
// Function to print the arrangement that// satisfies the given conditionstatic void printArrangement(int []a, int n){Â
    // Sort the array initially    Array.Sort(a);Â
    // Array that stores the arrangement    int []b = new int[n];Â
    // Once the array is sorted    // Re-fill the array again in the    // mentioned way in the approach    int low = 0, high = n - 1;    for (int i = 0; i < n; i++)     {        if (i % 2 == 0)            b[low++] = a[i];        else            b[high--] = a[i];    }Â
    // Iterate in the array    // and check if the arrangement made    // satisfies the given condition or not    for (int i = 0; i < n; i++)    {Â
        // For the first element        // the adjacents will be a[1] and a[n-1]        if (i == 0)        {            if (b[n - 1] + b[1] <= b[i])            {                Console.Write(-1);                return;            }        }Â
        // For the last element        // the adjacents will be a[0] and a[n-2]        else if (i == (n - 1))         {            if (b[n - 2] + b[0] <= b[i])            {                Console.Write(-1);                return;            }        }        else        {            if (b[i - 1] + b[i + 1] <= b[i])            {                Console.Write(-1);                return;            }        }    }Â
    // If we reach this position then    // the arrangement is possible    for (int i = 0; i < n; i++)        Console.Write(b[i] + " ");}Â
// Driver codepublic static void Main () {Â Â Â Â int []a = { 1, 4, 4, 3, 2 };Â Â Â Â int n = a.Length;Â
    printArrangement(a, n);}}Â
// This code is contributed by anuj_67.. |
Javascript
<script>// javascript implementation of the approachÂ
    // Function to print the arrangement that    // satisfies the given condition    function printArrangement(a, n)    {Â
        // Sort the array initially        a.sort();Â
        // Array that stores the arrangement        var b = Array(n).fill(0);Â
        // Once the array is sorted        // Re-fill the array again in the        // mentioned way in the approach        var low = 0, high = n - 1;        for (i = 0; i < n; i++) {            if (i % 2 == 0)                b[low++] = a[i];            else                b[high--] = a[i];        }Â
        // Iterate in the array        // and check if the arrangement made        // satisfies the given condition or not        for (i = 0; i < n; i++) {Â
            // For the first element            // the adjacents will be a[1] and a[n-1]            if (i == 0) {                if (b[n - 1] + b[1] <= b[i]) {                    document.write(-1);                    return;                }            }Â
            // For the last element            // the adjacents will be a[0] and a[n-2]            else if (i == (n - 1)) {                if (b[n - 2] + b[0] <= b[i]) {                    document.write(-1);                    return;                }            } else {                if (b[i - 1] + b[i + 1] <= b[i]) {                    document.write(-1);                    return;                }            }        }Â
        // If we reach this position then        // the arrangement is possible        for (i = 0; i < n; i++)            document.write(b[i] + " ");    }Â
    // Driver code        var a = [ 1, 4, 4, 3, 2 ];        var n = a.length;Â
        printArrangement(a, n);Â
// This code is contributed by todaysgaurav </script> |
1 3 4 4 2
Â
Time Complexity: O(N log N)Â //the inbuilt sort function takes N log N time to complete all operations, hence the overall time taken by the algorithm is N log N
Auxiliary Space: O(n) // an extra array is used to store all the elements and in worst case all elements will be stored hence algorithm takes up linear space
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



