Permuting Two Arrays Hacker Rank Solution Best & Easiest

Permuting Two Arrays Problem Solution
Permuting Two Arrays Problem Solution

In this post, we will solve Permuting Two Arrays HackerRank Solution. This problem (Permuting Two Arrays) is a part of the HackerRank Problem Solving series.

Given two arrays of equal size n and an integer k. The task is to permute both arrays such that sum of their corresponding element is greater than or equal to k i.e a[i] + b[i] >= k. The task is print “Yes” if any such permutation exists, otherwise print “No”.

Permuting Two Arrays Hacker Rank Solution

Problem solution in Python programming:

def twoArrays(k, A, B):
    A.sort()
    B.sort(reverse = True)
    for i in range(n):
        if A[i] + B[i] < k:
            return "NO"
    return "YES"

Problem solution in JavaScript programming:

function twoArrays(k, A, B) {
  let counter = 0;
  A.sort((a, b) => a - b);
  B.sort((a, b) => a - b).reverse();

  for (let i = 0; i < A.length; i++) {
    if (A[i] + B[i] >= k) {
      counter++;
    }
  }

  if (counter === A.length) {
    return `YES`;
  } else {
    return `NO`;
  }
}

Problem solution in C++ programming:

string twoArrays(int k, vector<int> A, vector<int> B) {
    sort(A.begin(),A.end());
    sort(B.begin(),B.end(),greater<int>());
    for(int i=0;i<A.size();i++)
    {
        if(A[i]+B[i]<k)
            return "NO";
    }
    return "YES";
}

Problem solution in Ruby programming:

def twoArrays(k, a, b)
    a.sort!
    b.sort!.reverse!
    
    for i in 0..a.length - 1
      return 'NO' if a[i] + b[i] < k
    end
    'YES'
end