Open In App

Rearrange Array to maximize number having Array elements as digits based on given conditions

Improve
Improve
Like Article
Like
Save
Share
Report

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 1 2 
Explanation: 
Since arr[0] is less than arr[2], so swap them. Therefore the maximum possible number from the array is 4, 3, 1, 2.

Input: arr[] = { 1, 3, 456, 6, 7, 8 }, str = “101101” 
Output: 8 7 6 456 3 1 
Explanation: 
Array elements present at 0-chractered indices: {3, 7} 
Largest number that can be formed from the above two numbers is 73 
Array elements present at 1-chractered indices: {1, 456, 6, 8} 
Largest number that can be formed from the above two numbers is 864561 
Therefore, maximum number that can be generated from the array is 87645631 

 Approach: Follow the steps below to solve the problem: 

  1. Create two arrays to store 0-charactered index elements and 1-charactered index elements from the array.
  2. Sort the arrays to form largest possible numbers from these two arrays.
  3. Iterate over str and based on the characters, place array elements from the sorted arrays.

Below is the implementation of the above approach: 

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Comparison Function to sort()
int myCompare(int a, int b)
{
    string X = to_string(a);
    string Y = to_string(b);
 
    // Append Y at the end of X
    string XY = X.append(Y);
 
    // Append X at the end of Y
    string YX = Y.append(X);
 
    // Compare and return greater
    return XY.compare(YX) < 0 ? 1 : 0;
}
 
// Function to return the rearranged
// array in the form of largest
// possible number that can be formed
void findMaxArray(vector<int>& arr, string& str)
{
    int N = arr.size();
    vector<int> Z, O, ans(N);
 
    for (int i = 0; i < N; i++) {
        if (str[i] == '0') {
            Z.push_back(arr[i]);
        }
 
        else {
            O.push_back(arr[i]);
        }
    }
 
    // Sort them in decreasing order
    sort(Z.rbegin(), Z.rend(), myCompare);
    sort(O.rbegin(), O.rend(), myCompare);
 
    int j = 0, k = 0;
 
    // Generate the sorted array
    for (int i = 0; i < N; i++) {
        if (str[i] == '0') {
            ans[i] = Z[j++];
        }
        else {
            ans[i] = O[k++];
        }
    }
 
    for (int i = 0; i < N; i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 3, 456, 6, 7, 8 };
    string str = "101101";
    findMaxArray(arr, str);
    return 0;
}


Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
 
// Function to return the rearranged
// array in the form of largest
// possible number that can be formed
static void findMaxArray(int[] arr, String str)
{
    int N = arr.length;
    ArrayList<Integer> Z = new ArrayList<>(), O = new ArrayList<>();
                        
    int[] ans = new int[N];
 
    for(int i = 0; i < N; i++)
    {
        if (str.charAt(i) == '0')
        {
            Z.add(arr[i]);
        }
        else
        {
            O.add(arr[i]);
        }
    }
 
    // Sort them in decreasing order
    Collections.sort(Z, new Comparator<Integer>()
    {
        public int compare(Integer a, Integer b)
        {
            String X = Integer.toString(a);
            String Y = Integer.toString(b);
             
            // Append Y at the end of X
            String XY = X + Y;
         
            // Append X at the end of Y
            String YX = Y + X;
         
            // Compare and return greater
            return XY.compareTo(YX) > 0 ? -1 : 1;
        }
    });
     
    Collections.sort(O, new Comparator<Integer>()
    {
        public int compare(Integer a, Integer b)
        {
            String X = Integer.toString(a);
            String Y = Integer.toString(b);
 
            // Append Y at the end of X
            String XY = X + Y;
         
            // Append X at the end of Y
            String YX = Y + X;
         
            // Compare and return greater
            return XY.compareTo(YX) > 0 ? -1 : 1;
        }
    });
     
    int j = 0, k = 0;
 
    // Generate the sorted array
    for(int i = 0; i < N; i++)
    {
        if (str.charAt(i) == '0')
        {
            ans[i] = Z.get(j++);
        }
        else
        {
            ans[i] = O.get(k++);
        }
    }
 
    for(int i = 0; i < N; i++)
    {
        System.out.print(ans[i] + " ");
    }
}
 
// Driver code
public static void main (String[] args)
{
    int[] arr = { 1, 3, 456, 6, 7, 8 };
    String str = "101101";
     
    findMaxArray(arr, str);
}
}
 
// This code is contributed by offbeat


Python3




# Python Program to implement
# the above approach
from functools import cmp_to_key
 
# Function to return the rearranged
# array in the form of largest
# possible number that can be formed
def findMaxArray(arr, strr):
    N = len(arr)
    Z = []
    O = []
    ans = [0]*N
 
    for i in range(N):
        if (strr[i] == '0'):
            Z.append(arr[i])
        else:
            O.append(arr[i])
 
    # Sort them in decreasing order
    Z.sort(key=cmp_to_key(lambda x, y: 1 if str(x)+str(y) < str(y)+str(x) else -1))
    O.sort(key=cmp_to_key(lambda x, y: 1 if str(x)+str(y) < str(y)+str(x) else -1))
 
    j = 0
    k = 0
 
    # Generate the sorted array
    for i in range(N):
        if (strr[i] == '0'):
            ans[i] = Z[j]
            j += 1
        else:
            ans[i] = O[k]
            k += 1
 
    for i in range(N):
        print(ans[i], end=" ")
 
# Driver Code
arr = [1, 3, 456, 6, 7, 8]
strr = "101101"
findMaxArray(arr, strr)
 
# This code is contributed by rj13to.


Javascript




// Javascript program to implement
// the above approach
function compare( a, b)
{
    let X = a.toString();
    let Y = b.toString();
     
    // Append Y at the end of X
    let XY = X + Y;
 
    // Append X at the end of Y
    let YX = Y + X;
 
    // Compare and return greater
    return XY.localeCompare(YX) > 0 ? -1 : 1;
}
 
// Function to return the rearranged
// array in the form of largest
// possible number that can be formed
function findMaxArray( arr,  str)
{
 let N = arr.length;
 let Z = [];
    let O = [];
       
    let ans = [];
    for(let i=0;i<N;i++)
    {
        ans.push(0);
    }
 
 for (let i = 0; i < N; i++) {
  if (str[i] == '0') {
   Z.push(arr[i]);
  }
 
  else {
   O.push(arr[i]);
  }
 }
 
 // Sort them in decreasing order
    Z.sort(compare);
 
    O.sort(compare);
  
 let j = 0, k = 0;
 
 // Generate the sorted array
 for(let i = 0; i < N; i++)
 {
  if (str[i] == '0')
  {
   ans[i] = Z[j++];
  }
  else
  {
   ans[i] = O[k++];
  }
 }
 
    console.log(ans);
}
 
// Driver code
let arr = [ 1, 3, 456, 6, 7, 8 ];
let str = "101101";
  
findMaxArray(arr, str);
 
// This code is contributed by harimahecha


C#




// Include namespace system
using System;
using System.Collections.Generic;
 
 
 
public class GFG
{
    // Function to return the rearranged
    // array in the form of largest
    // possible number that can be formed
    public static void findMaxArray(int[] arr, String str)
    {
        var N = arr.Length;
        var Z = new List<int>();
        var O = new List<int>();
        int[] ans = new int[N];
        for (int i = 0; i < N; i++)
        {
            if (str[i] == '0')
            {
                Z.Add(arr[i]);
            }
            else
            {
                O.Add(arr[i]);
            }
        }
        // Sort them in decreasing order
        Z.Sort((a,b) =>{
            var X = Convert.ToString(a);
            var Y = Convert.ToString(b);
            // Append Y at the end of X
            var XY = X + Y;
            // Append X at the end of Y
            var YX = Y + X;
            // Compare and return greater
            return string.CompareOrdinal(XY,YX) > 0 ? -1 : 1;
        });
        O.Sort((a,b) =>{
            var X = Convert.ToString(a);
            var Y = Convert.ToString(b);
            // Append Y at the end of X
            var XY = X + Y;
            // Append X at the end of Y
            var YX = Y + X;
            // Compare and return greater
            return string.CompareOrdinal(XY,YX) > 0 ? -1 : 1;
        });
         
        var j = 0;
        var k = 0;
        // Generate the sorted array
        for (int i = 0; i < N; i++)
        {
            if (str[i] == '0')
            {
                ans[i] = Z[j++];
            }
            else
            {
                ans[i] = O[k++];
            }
        }
        for (int i = 0; i < N; i++)
        {
            Console.Write(ans[i].ToString() + " ");
        }
    }
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = {1, 3, 456, 6, 7, 8};
        var str = "101101";
        GFG.findMaxArray(arr, str);
    }
}


Output: 

8 7 6 456 3 1

 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)
 



Last Updated : 11 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads