The Wayback Machine - https://web.archive.org/web/20240823160309/https://www.geeksforgeeks.org/rearrange-two-given-arrays-such-that-sum-of-same-indexed-elements-lies-within-given-range/
Open In App

Rearrange two given arrays such that sum of same indexed elements lies within given range

Last Updated : 08 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
60.7%
25.4K

Given two arrays arr1[] and arr2[] consisting of N positive integers and an even integer K, the task is to check if the sum of the same indexed elements in the two arrays lie in the range [K/2, K] after rearranging the given arrays or not. If it is possible to obtain such an arrangement, then print “Yes”. Otherwise, print “No”.

Examples:

Input: arr1[] = {1, 4, 3, 5}, arr2[] = {0, 2, 1, 1}, K = 6
Output: Yes
Explanation: Rearranging arr1[] to {1, 4, 3, 5} and arr2[] to {2, 0, 1, 1} ensures that the sum of same indexed elements lie in the range [3, 6]. Therefore, print “Yes”.

Input: arr1[] = {2, 0}, arr2[] = {3, 4}, K = 2
Output: No
Explanation: No such arrangement is possible

Naive Approach: The simplest approach to generate all possible permutations of the given arrays and check if any possible arrangements satisfy the given conditions or not. If found to be true, then print “Yes”. Otherwise, print “No”. 

Time Complexity: O((N!)2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if there exists any
// arrangements of the arrays such that
// sum of element lie in the range [K/2, K]
void checkArrangement(int A1[], int A2[],
                      int n, int k)
{
    // Sort the array arr1[] in
    // increasing order
    sort(A1, A1 + n);
 
    // Sort the array arr2[] in
    // decreasing order
    sort(A2, A2 + n, greater<int>());
 
    int flag = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // If condition is not satisfied
        // break the loop
        if ((A1[i] + A2[i] > k)
            || (A1[i] + A2[i] < k / 2)) {
 
            flag = 1;
            break;
        }
    }
 
    // Print the result
    if (flag == 1)
        cout << "No";
    else
        cout << "Yes";
}
 
// Driver Code
int main()
{
    int arr1[] = { 1, 3, 4, 5 };
    int arr2[] = { 2, 0, 1, 1 };
 
    int K = 6;
 
    int N = sizeof(arr1)
 
            / sizeof(arr1[0]);
 
    checkArrangement(arr1, arr2, N, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG{
 
// Function to check if there exists any
// arrangements of the arrays such that
// sum of element lie in the range [K/2, K]
static void checkArrangement(Integer[] A1,
                             Integer[] A2,
                             int n, int k)
{
     
    // Sort the array arr1[] in
    // increasing order
    Arrays.sort(A1);
 
    // Sort the array arr2[] in
    // decreasing order
    Arrays.sort(A2, Collections.reverseOrder());
 
    int flag = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // If condition is not satisfied
        // break the loop
        if ((A1[i] + A2[i] > k) ||
            (A1[i] + A2[i] < k / 2))
        {
            flag = 1;
            break;
        }
    }
 
    // Print the result
    if (flag == 1)
        System.out.println("No");
    else
        System.out.println("Yes");
}
 
// Driver Code
public static void main(String[] args)
{
    Integer[] arr1 = { 1, 3, 4, 5 };
    Integer[] arr2 = { 2, 0, 1, 1 };
 
    int K = 6;
 
    int N = arr1.length;
 
    checkArrangement(arr1, arr2, N, K);
}
}
 
// This code is contributed by akhilsaini


Python3




# Python3 program for the above approach
 
# Function to check if there exists any
# arrangements of the arrays such that
# sum of element lie in the range [K/2, K]
def checkArrangement(A1, A2, n, k):
     
    # Sort the array arr1[] in
    # increasing order
    A1 = sorted(A1)
 
    # Sort the array arr2[] in
    # decreasing order
    A2 = sorted(A2)
 
    A2 = A2[::-1]
 
    flag = 0
 
    # Traverse the array
    for i in range(n):
 
        # If condition is not satisfied
        # break the loop
        if ((A1[i] + A2[i] > k) or
            (A1[i] + A2[i] < k // 2)):
            flag = 1
            break
 
    # Print the result
    if (flag == 1):
        print("No")
    else:
        print("Yes")
 
# Driver Code
if __name__ == '__main__':
     
    arr1 = [ 1, 3, 4, 5 ]
    arr2 = [ 2, 0, 1, 1 ]
 
    K = 6
 
    N = len(arr1)
 
    checkArrangement(arr1, arr2, N, K)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections;
 
class GFG{
 
// Function to check if there exists any
// arrangements of the arrays such that
// sum of element lie in the range [K/2, K]
static void checkArrangement(int[] A1, int[] A2,
                             int n, int k)
{
     
    // Sort the array arr1[] in
    // increasing order
    Array.Sort(A1);
 
    // Sort the array arr2[] in
    // decreasing order
    Array.Sort(A2);
    Array.Reverse(A2);
 
    int flag = 0;
 
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
         
        // If condition is not satisfied
        // break the loop
        if ((A1[i] + A2[i] > k) ||
            (A1[i] + A2[i] < k / 2))
        {
            flag = 1;
            break;
        }
    }
 
    // Print the result
    if (flag == 1)
        Console.WriteLine("No");
    else
        Console.WriteLine("Yes");
}
 
// Driver Code
public static void Main()
{
    int[] arr1 = { 1, 3, 4, 5 };
    int[] arr2 = { 2, 0, 1, 1 };
 
    int K = 6;
 
    int N = arr1.Length;
 
    checkArrangement(arr1, arr2, N, K);
}
}
 
// This code is contributed by akhilsaini


Javascript




<script>
 
// JavaScript program for
// the above approach
 
// Function to check if there exists any
// arrangements of the arrays such that
// sum of element lie in the range [K/2, K]
function checkArrangement( A1, A2, n, k)
{
      
    // Sort the array arr1[] in
    // increasing order
    A1.sort();
  
    // Sort the array arr2[] in
    // decreasing order
    A2.sort();
    A2.reverse();
  
    let flag = 0;
  
    // Traverse the array
    for(let i = 0; i < n; i++)
    {
          
        // If condition is not satisfied
        // break the loop
        if ((A1[i] + A2[i] > k) ||
            (A1[i] + A2[i] < k / 2))
        {
            flag = 1;
            break;
        }
    }
  
    // Print the result
    if (flag == 1)
        document.write("No");
    else
        document.write("Yes");
}
 
// Driver Code
 
    let arr1 = [ 1, 3, 4, 5 ];
    let arr2 = [ 2, 0, 1, 1 ];
  
    let K = 6;
  
    let N = arr1.length;
  
    checkArrangement(arr1, arr2, N, K);
           
</script>


Output: 

Yes

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)



Similar Reads

Bitwise XOR of same indexed array elements after rearranging an array to make XOR of same indexed elements of two arrays equal
Given two arrays A[] and B[] consisting of N positive integers, the task is to the Bitwise XOR of same indexed array elements after rearranging the array B[] such that the Bitwise XOR of the same indexed elements of the arrays A[] becomes equal. Examples: Input: A[] = {1, 2, 3}, B[] = {4, 6, 7}Output: 5Explanation:Below are the possible arrangement
14 min read
Rearrange two given arrays to maximize sum of same indexed elements
Given two arrays A[] and B[] of size N, the task is to find the maximum possible sum of abs(A[i] – B[i]) by rearranging the array elements. Examples: Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}Output: 12Explanation: One of the possible rearrangements of A[] is {5, 4, 3, 2, 1}. One of the possible rearrangements of B[] is {1, 2, 3, 4, 4}. Th
5 min read
Minimize sum of product of same-indexed elements of two arrays by reversing a subarray of one of the two arrays
Given two equal-length arrays A[] and B[], consisting only of positive integers, the task is to reverse any subarray of the first array such that sum of the product of same-indexed elements of the two arrays, i.e. (A[i] * B[i]) is minimum. Examples: Input: N = 4, A[] = {2, 3, 1, 5}, B[] = {8, 2, 4, 3} Output: A[] = 1 3 2 5 B[] = 8 2 4 3 Minimum pro
12 min read
Rearrange array such that sum of same indexed elements is atmost K
Given two arrays A[] and B[] consisting of N integers each and an integer K, the task is to rearrange the array B[] such that sum of Ai + Bi is atmost K. If no such arrangement is possible, print -1. Examples: Input: A[] = {1, 2, 3, 4, 2}, B[] = {1, 2, 3, 1, 1}, K = 5Output: 1 3 1 1 2 Input: A[] = {1, 2, 3, 4, 5}, B[] = {2, 3, 4, 5, 6}, K = 6Output
6 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
Generate a pair of integers from a range [L, R] whose LCM also lies within the range
Given two integers L and R, the task is to find a pair of integers from the range [L, R] having LCM within the range [L, R] as well. If no such pair can be obtained, then print -1. If multiple pairs exist, print any one of them. Examples: Input: L = 13, R = 69Output: X =13, Y = 26Explanation: LCM(x, y) = 26 which satisfies the conditions L ? x &lt;
4 min read
Rearrange an array to maximize sum of Bitwise AND of same-indexed elements with another array
Given two arrays A[] and B[] of sizes N, the task is to find the maximum sum of Bitwise AND of same-indexed elements in the arrays A[] and B[] that can be obtained by rearranging the array B[] in any order. Examples: Input: A[] = {1, 2, 3, 4}, B[] = {3, 4, 1, 2}Output: 10Explanation: One possible way is to obtain the maximum value is to rearrange t
15 min read
Maximize sum of product of same-indexed elements of equal length subarrays obtained from two given arrays
Given two arrays arr[] and brr[] of size N and M integers respectively, the task is to maximize the sum of the product of the same-indexed elements of two subarrays of an equal length with the selected subarray from the array brr[] being reversed. Examples: Input: arr[] = {-1, 3, -2, 4, 5}, brr[] = {4, -5}Output: 26Explanation:Subarrays selected fr
13 min read
Minimum swaps of same-indexed elements required to make sum of two given arrays even
Given two arrays arr1[] and arr2[] of size N, the task is to count the minimum number of swaps of same-indexed elements from both the arrays arr1[] and arr2[] required to make the sum of all elements of both the arrays even. If it is not possible, then print "-1". Examples: Input: arr1[] = {1, 4, 2, 3}, arr2[] = {2, 3, 4, 1}Output: 0Explanation: Su
9 min read
Minimize sum of absolute differences of same-indexed elements of two given arrays by at most one replacement
Given two arrays A[] and B[] of size N each, the task is to find the minimum possible sum of absolute difference of same indexed elements of the two arrays, i.e. sum of |A[i] - B[i]| for all i such that 0 ? i &lt; N by replacing at most one element in A[] with another element of A[]. Examples: Input: A[] = {6, 4, 1, 9, 7, 5}, B[] = {3, 9, 7, 4, 2,
10 min read
Construct two N-length arrays with same-indexed elements as co-prime and a difference of N in their sum
Given a positive integer N, the task is to generate two arrays of length N such that the same-indexed elements of both the arrays are co-prime and absolute difference between the sum of elements of the arrays is N. Examples: Input: N = 5Output: {1, 3, 5, 7, 9} {2, 4, 6, 8, 10}Explanation: Pairs of same-indexed elements are (1, 2), (3, 4), (5, 6), (
6 min read
Reduce sum of same-indexed elements of two arrays to less than K by rearranging the second array
Given two arrays arr1[] and arr2[], both of size N and an integer X, the task is to check if the sum of same-indexed elements of both the arrays at corresponding indices can be made at most K after rearranging the second array. If it is possible then print "Yes" else print "No". Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 1, 2}, X = 4Output:
6 min read
Rearrange arrays such that sum of corresponding elements is same for all equal indices
Given two arrays A[] and B[] of length N. Then your task is to rearrange the elements of both arrays in such a way that the sum (Ai + Bi) for all i (1 &lt;= i &lt;= N) is same. If no such arrangement is possible output -1 instead. Examples: Input: N = 3, A[] = {1, 2, 3}, B[] = {1, 2, 3}Output: A[] = {3, 1, 2}, B[] = {1, 3, 2}Explanation: Rearranged
12 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
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Maximum length of same indexed subarrays from two given arrays satisfying the given condition
Given two arrays arr[] and brr[] and an integer C, the task is to find the maximum possible length, say K, of the same indexed subarrays such that the sum of the maximum element in the K-length subarray in brr[] with the product between K and sum of the K-length subarray in arr[] does not exceed C. Examples: Input: arr[] = {2, 1, 3, 4, 5}, brr[] =
15+ min read
Find two distinct numbers such that their LCM lies in given range
Given two numbers L and R, the task is to find two distinct minimum positive integers X and Y such that whose LCM lies in the range [L, R]. If there doesn't exist any value of X and Y then print "-1". Examples: Input: L = 3, R = 8 Output: x = 3, y=6Explanation:LCM of 3 and 6 is 6 which is in range 3, 8 Input: L = 88, R = 90Output: -1Explanation:Min
4 min read
Minimum sum of two elements from two arrays such that indexes are not same
Given two arrays a[] and b[] of same size. Task is to find minimum sum of two elements such that they belong to different arrays and are not at same index in their arrays. Examples: Input : a[] = {5, 4, 13, 2, 1} b[] = {2, 3, 4, 6, 5}Output : 3We take 1 from a[] and 2 from b[]Sum is 1 + 2 = 3.Input : a[] = {5, 4, 13, 1} b[] = {3, 2, 6, 1}Output : 3
15+ min read
Maximize score of same-indexed subarrays selected from two given arrays
Given two arrays A[] and B[], both consisting of N positive integers, the task is to find the maximum score among all possible same-indexed subarrays in both the arrays such that the score of any subarray over the range [L, R] is calculated by the maximum of the values (AL*BL + AL + 1*BL + 1 + ... + AR*BR) + (AR*BL + AR - 1*BL + 1 + ... + AL*BR). E
15+ min read
Minimum swaps of similar indexed elements required to make all elements of one of the two given arrays equal
Given two arrays A[] and B[] of size N, the task is to count the minimum number of swaps of similar indexed elements required to make one of the two given arrays equal. If it is not possible to make all elements of an array equal, then print -1. Examples: Input: A[] = {3, 4, 1, 3, 1, 3, 4}, B[] = {1, 3, 3, 1, 3, 4, 3}Output: 3Explanation: Swapping
12 min read
Minimize swap between same indexed elements to make given Arrays strictly increasing
Given two arrays arr1[] and arr2[] of size N each, the task is to find the minimum number of interchange of the same indexed elements required to make both arrays strictly increasing. Note: Return -1 if it is not possible to make them strictly increasing. Examples: Input: arr1 = {1, 3, 5, 4}, arr2 = {1, 2, 3, 7}Output: 1Explanation: Swap arr1[3] an
10 min read
Generate an N-length array with sum equal to twice the sum of its absolute difference with same-indexed elements of given array
Given an array arr[] of size N, the task is to construct an array brr[] of size N that satisfies the following conditions: In every pair of consecutive elements in the array brr[], one element must be divisible by the other, i.e. brr[i] must be divisible by brr[i + 1] or vice-versa.Every ith element in the array brr[] must satisfy brr[i] &gt;= arr[
5 min read
Rearrange an array such that every odd indexed element is greater than it previous
Given an unsorted array, rearrange the array such that the number at the odd index is greater than the number at the previous even index. There may be multiple outputs, we need to print one of them. Note: Indexing is based on an array, so it always starts from 0. Examples: Input : arr[] = {5, 2, 3, 4} Output : arr[] = {2, 5, 3, 4} Input : arr[] = {
7 min read
Maximize product of same-indexed elements of same size subsequences
Given two integer arrays a[] and b[], the task is to find the maximum possible product of the same indexed elements of two equal length subsequences from the two given arrays. Examples: Input: a[] = {-3, 1, -12, 7}, b[] = {3, 2, -6, 7} Output: 124 Explanation: The subsequence [1, -12, 7] from a[] and subsequence [3, -6, 7] from b[] gives the maximu
14 min read
Minimum swaps of same indexed elements required to obtain a Majority Element in one of the arrays
Given two arrays arr[] and brr[] of length N, the task is to find the minimum number of swaps of the same indexed elements required such an element occurs at least half of the indices in the array arr[], i.e. Majority element. If it is not possible to obtain such an arrangement, then print "-1". Examples: Input: arr[] = {3, 2, 1, 4, 9}, brr[] = {5,
10 min read
Minimize cost of increments or decrements such that same indexed elements become multiple of each other
Given two arrays A[] and B[] consisting of N integers, the task is to minimize the total cost of incrementing or decrementing array elements by 1 such that for every ith element, either A[i] is a multiple of B[i] or vice-versa. Examples: Input: A[] = {3, 6, 3}, B[] = {4, 8, 13}Output: 4Explanation:Incrementing A[0] by 1 (3 + 1 = 4) makes it multipl
6 min read
Maximize minimum of array generated by maximums of same indexed elements of two rows of a given Matrix
Given a matrix mat[][] of N rows and M columns, the task is to choose any two rows(i, j) (0 ? i, j ? N - 1) and construct a new array A[] of size M, where A[k] = max(mat[i][k], mat[j][k]) such that minimum of A[] is maximum possible. Examples: Input: mat[][] = {{5, 0, 3, 1, 2}, {1, 8, 9, 1, 3}, {1, 2, 3, 4, 5}, {9, 1, 0, 3, 7}, {2, 3, 0, 6, 3}, {6,
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
Maximum time such that absolute difference between hour and minute lies in given range
Given a 24-hour time value, where on some numbers are question marks( '?' ), and two integers L and R. The question mark can be replaced with any number. The task is to find the maximum time such that the absolute difference between hour value and minute value lies in the interval [L, R]. If no possible value of time exists, then print -1. Examples
13 min read
Maximum cost of a value over the range [1, N] such that values lies in at most K given ranges
Given a positive integer N and an array arr[] of size M of the type {L, R, C} such that C is the cost of choosing an element in the range [L, R] and a positive integer K, the task is to find the maximum cost of a value over the range [1, N] such that values lies in at most K given range arr[]. Examples: Input: arr[] = {{2, 8, 800}, {6, 9, 1500}, {4
8 min read