In this Permuting Two Arrays HackerRank Problem,
There are two -element arrays of integers, and . Permute them into some and such that the relation holds for all where .
There will be queries consisting of , , and . For each query, return YES
if some permutation , satisfying the relation exists. Otherwise, return NO
.
Example
A valid is and : and . Return YES
.
Function Description
Complete the twoArrays function in the editor below. It should return a string, either YES
or NO
.
twoArrays has the following parameter(s):
- int k: an integer
- int A[n]: an array of integers
- int B[n]: an array of integers
Returns
– string: either YES
or NO
Input Format
The first line contains an integer , the number of queries.
The next sets of lines are as follows:
- The first line contains two space-separated integers and , the size of both arrays and , and the relation variable.
- The second line contains space-separated integers .
- The third line contains space-separated integers .
Constraints
Sample Input
STDIN Function
----- --------
2 q = 2
3 10 A[] and B[] size n = 3, k = 10
2 1 3 A = [2, 1, 3]
7 8 9 B = [7, 8, 9]
4 5 A[] and B[] size n = 4, k = 5
1 2 2 1 A = [1, 2, 2, 1]
3 3 3 4 B = [3, 3, 3, 4]
Sample Output
YES
NO
Explanation
There are two queries:
- Permute these into and so that the following statements are true:
- , , and . To permute and into a valid and , there must be at least three numbers in that are greater than .
Permuting Two Arrays Hacker Rank Problem Solutions
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in C#
public static string TwoArrays(int k, List<int> A, List<int> B)
{
A.Sort();
B.Sort();
B.Reverse();
for (int i = 0; i < A.Count; i++)
{
if (A[i] + B[i] < k)
{
return "NO";
}
}
return "YES";
}
Problem Solution in JavaScript
function twoArrays(k, A, B) {
// Write your code here
const a = A.sort((a,b) => a - b)
const b = B.sort((a,b) => b - a)
for(let i = 0; i < a.length; i++) if(a[i] + b[i] < k) return 'NO';
return 'YES'
}
Problem Solution in PHP
function twoArrays($k, $A, $B) {
// Write your code here
$c = count($A) - 1;
$result = true;
sort($A);
rsort($B);
for($i = 0; $i <= $c; $i++){
$sum = $A[$i] + $B[$i];
if($sum < $k){
$result = false;
}
}
return $result == false ? 'NO' : 'YES';
}
Problem Solution in Python
def twoArrays(k, A, B):
A = sorted(A)
B = sorted(B, reverse=True)
if any(list(map(lambda x,y: x+y<k, A, B))):
return 'NO'
return 'YES'
Leave a Reply