Skip to problem
←

Pair Arrays to Meet a Minimum Sum

Easy 0 attempts

Given two equal-length integer arrays A and B and an integer threshold k, return whether their entries can be rearranged so that every paired sum A[i] + B[i] is at least k.

Each entry must be used exactly once. Repeated values are separate entries, and equality with k is allowed. Return a boolean, not the rearranged arrays. You may reorder both input arrays.

For A = [2, 1, 3], B = [7, 8, 9], and k = 10, pair [1, 2, 3] with [9, 8, 7]. All three sums equal 10. A large total sum alone does not guarantee that every pair can reach the threshold.

Function contract

Implement canPermute(A, B, k).

Output: Return true if a one-to-one pairing makes every sum at least k; otherwise return false.

Example 1

Input
A = [2,1,3]
B = [7,8,9]
k = 10
Output
true

Example 2

Input
A = [1,2]
B = [1,2]
k = 5
Output
false
Constraints
  • 1 <= A.length == B.length <= 10^5
  • 1 <= A[i], B[i] <= 10^6
  • k is a safe JavaScript integer.

Sort + Greedy

Sort A ascending and B descending, then check every paired sum.

Why is this sufficient? Consider the smallest remaining value a in A and the largest remaining value b in B. If a + b < k, no partner can work for a. Otherwise, if any valid pairing exists, suppose it pairs a with b′ and b with a′. Swap those partners. The new pair a + b is valid, and a′ + b′ >= a + b′ >= k because a′ >= a. Thus pairing the smallest with the largest preserves feasibility.

Repeat this argument for the remaining entries. Both arrays are sorted in place; the algorithm returns only whether all pairs qualify.

javascript
function canPermute(A, B, k) {
  A.sort((a, b) => a - b);
  B.sort((a, b) => b - a);
  return A.every((a, i) => a + B[i] >= k);
}

Time: O(n log n) | Space: O(n) as a conservative bound including JavaScript sorting workspace; the pairing scan itself uses O(1) extra space.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript