Open In App

Check whether an array can be fit into another array rearranging the elements in the array

Last Updated : 01 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Share
4 Likes
Like
Report

Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array.

Examples

Input : A[] = { 7, 5, 3, 2 }, B[] = { 5, 4, 8, 7 }
Output : YES 
Rearrange the first array to {3, 2, 7, 5} 
Do not rearrange the second array's element. 
After rearranging, all Ai<=Bi. 

Input : A[] = { 7, 5, 3, 2, 5, 105, 45, 10 }, B[] = { 2, 4, 0, 5, 6, 9, 75, 84 }
Output : NO

Approach: Sort both the arrays and check whether Ai is less than or equal to Bi for all 0 ≤ i ≤ N. If at any ith position Ai is greater than Bi return false, otherwise return true. 

Steps to solve the problem:

  • Sort array A in non-decreasing order.
  • Sort array B in non-decreasing order.
  •  For each element i from 0 to N-1 do the following:
    •  If A[i] > B[i], return false.
  • If the loop completes without returning false, return true.

Below is the implementation of the above approach: 

C++
// C++ Program to check whether an array
// can be fit into another array with given
// condition.
#include <bits/stdc++.h>
using namespace std;

// Returns true if the array A can be fit into
// array B, otherwise false
bool checkFittingArrays(int A[], int B[], int N)
{
    // Sort both the arrays
    sort(A, A + N);
    sort(B, B + N);

    // Iterate over the loop and check whether every
    // array element of A is less than or equal to
    // its corresponding array element of B
    for (int i = 0; i < N; i++)
        if (A[i] > B[i])
            return false;

    return true;
}

// Driver Code
int main()
{
    int A[] = { 7, 5, 3, 2 };
    int B[] = { 5, 4, 8, 7 };
    int N = sizeof(A) / sizeof(A[0]);

    if (checkFittingArrays(A, B, N))
        cout << "YES";
    else
        cout << "NO";
    return 0;
}
Java Python3 C# PHP JavaScript

Output
YES

Time Complexity: O(N * logN), where N is the size of the array.
Auxiliary Space: O(1)


Next Article
Article Tags :
Practice Tags :

Similar Reads