Arrange the numbers in the Array as per given inequalities - GeeksforGeeks

12 Jun, 2021
Given a list of N distinct integers and a list of N-1 inequality signs, the task is to insert the integers between the inequality signs, such that the final inequality formed always holds true.Note: The order of the inequality signs should not be changed.
Examples:
Input: Integers: [ 2, 5, 1, 0 ], Signs: [ <, >, < ]Output: 0 < 5 > 1 < 2 Explanation:The inequality formed is consistent and valid.
Input: Integers: [ 8, 34, 25, 1, -5, 10], Signs: [ >,  >, <, <, > ]Output: 34 > 25 > -5 < 1 < 10 > 8Explanation:The inequality formed is consistent and valid.
Approach: The list of inequality symbols can contain symbols in any order. So to obtain a consistent inequality, put the smallest integer left in the array before each < symbol and the largest integer left before each > symbol. Based on this idea, below are the steps:
Sort the list of integers in ascending order.Maintain two variables, say low and high, pointing at the first and last index of the list of integers.Iterate over the list of inequality symbols. If the current symbol is less, then add the integer pointed by low before <, and increment low to point to the next index. If the current symbol is greater, then add the integer pointed by high before >, and decrement high to point to the previous index.Finally, add the remaining element to the last position.
Sort the list of integers in ascending order.
Maintain two variables, say low and high, pointing at the first and last index of the list of integers.
Iterate over the list of inequality symbols. If the current symbol is less, then add the integer pointed by low before <, and increment low to point to the next index. If the current symbol is greater, then add the integer pointed by high before >, and decrement high to point to the previous index.
Finally, add the remaining element to the last position.
Below is the implementation of the above approach:
Java
Python3
C#
Javascript
// Java program for the above approachimport java.util.Arrays; public class PlacingNumbers {     // Function to place the integers    // in between the inequality signs    static String    formAnInequality(int[] integers,                     char[] inequalities)    {         // Sort the integers array and        // set the index of smallest        // and largest element        Arrays.sort(integers);         int lowerIndex = 0;        int higherIndex = integers.length - 1;         StringBuilder sb = new StringBuilder();         // Iterate over the inequalities        for (char ch : inequalities) {             // Append the necessary            // integers per symbol            if (ch == '<') {                sb.append(" "                          + integers[lowerIndex++]                          + " "                          + ch);            }            else {                sb.append(" "                          + integers[higherIndex--]                          + " "                          + ch);            }        }         // Add the final integer        sb.append(" " + integers[lowerIndex]);         // Return the answer        return sb.toString();    }     // Driver Code    public static void main(String[] args)    {        // Given List of Integers        int[] integers = { 2, 5, 1, 0 };         // Given list of inequalities        char[] inequalities = { '<', '>', '<' };         // Function Call        String output            = formAnInequality(integers,                               inequalities);         // Print the output        System.out.println(output);    }}
# Python3 program for# the above approach # Function to place the integers# in between the inequality signsdef formAnInequality(integers,                     inequalities):     # Sort the integers array and    # set the index of smallest    # and largest element    integers.sort()     lowerIndex = 0    higherIndex = len(integers) - 1    sb = ""     # Iterate over the inequalities    for ch in  inequalities:         # Append the necessary        # integers per symbol        if (ch == '<'):            sb += (" " + chr(integers[lowerIndex]) +                   " " + ch)            lowerIndex += 1        else:            sb += (" " + chr(integers[higherIndex]) +                   " " + ch)            higherIndex -= 1            # Add the final integer    sb += (" " + chr(integers[lowerIndex]))     # Return the answer    return sb # Driver Codeif __name__ ==  "__main__":         # Given List of Integers    integers = [2, 5, 1, 0]     # Given list of inequalities    inequalities = ['<', '>', '<']     # Function Call    output = formAnInequality(integers,                              inequalities)     # Print the output    print(output) # This code is contributed by Chitranayal
// C# program for the above approachusing System;using System.Text; class GFG{ // Function to place the integers// in between the inequality signsstatic StringformAnInequality(int[] integers,                char[] inequalities){         // Sort the integers array and    // set the index of smallest    // and largest element    Array.Sort(integers);     int lowerIndex = 0;    int higherIndex = integers.Length - 1;     StringBuilder sb = new StringBuilder();     // Iterate over the inequalities    foreach(char ch in inequalities)    {                 // Append the necessary        // integers per symbol        if (ch == '<')        {            sb.Append(" " + integers[lowerIndex++] +                      " " + ch);        }        else        {            sb.Append(" " + integers[higherIndex--] +                      " " + ch);        }    }     // Add the readonly integer    sb.Append(" " + integers[lowerIndex]);     // Return the answer    return sb.ToString();} // Driver Codepublic static void Main(String[] args){         // Given List of ints    int[] integers = { 2, 5, 1, 0 };     // Given list of inequalities    char[] inequalities = { '<', '>', '<' };     // Function call    String output = formAnInequality(integers,                                      inequalities);     // Print the output    Console.WriteLine(output);}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to place the integers// in between the inequality signsfunction formAnInequality(integers, inequalities){         // Sort the integers array and    // set the index of smallest    // and largest element    (integers).sort(function(a, b){return a - b;});     let lowerIndex = 0;    let higherIndex = integers.length - 1;     let sb = "";     // Iterate over the inequalities    for(let ch = 0; ch < inequalities.length; ch++)    {                 // Append the necessary        // integers per symbol        if (inequalities[ch] == '<')        {            sb += " " + (integers[lowerIndex++]) +                  " " + inequalities[ch];        }        else        {            sb += " " + (integers[higherIndex--]) +                  " " + inequalities[ch];        }    }     // Add the final integer    sb += " " + (integers[lowerIndex]);     // Return the answer    return sb;} // Driver Code // Given List of Integerslet integers = [ 2, 5, 1, 0 ]; // Given list of inequalitieslet inequalities = [ '<', '>', '<' ]; // Function Calllet output = formAnInequality(    integers, inequalities);     // Print the outputdocument.write(output); // This code is contributed by avanitrachhadiya2155 </script>
0 < 5 > 1 < 2
 
Time Complexity: O(N*log N) Auxiliary Space: O(1) 
29AjayKumar
ukasp
avanitrachhadiya2155
Maths
Arrays
Greedy
Mathematical
Sorting
Strings
Arrays
Strings
Greedy
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Trapping Rain Water
Find duplicates in O(n) time and O(1) extra space | Set 1
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3