Maximize disjoint k-sum pairs
Company: MathWorks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates proficiency in array algorithms, pairing logic, data structure selection, and complexity analysis, focusing on maximizing disjoint k-sum pairs and reasoning about space–time trade-offs.
Constraints
- 1 <= nums.length (problem-level); the function must also handle nums.length == 0 by returning 0
- Values and k may be negative or zero
- Each index may participate in at most one operation
- 1 <= nums.length <= 10^5 (typical interview bound)
Examples
Input: ([1, 2, 3, 4], 5)
Expected Output: 2
Explanation: Pair (1,4) and (2,3), both summing to 5. Two operations, no index reused.
Input: ([3, 1, 3, 4, 3], 6)
Expected Output: 1
Explanation: Only 3+3 = 6 works; there are three 3's, so one pair is formed and the remaining 3, plus 1 and 4, cannot be paired.
Input: ([], 5)
Expected Output: 0
Explanation: Empty array — no pairs possible, return 0.
Input: ([5], 5)
Expected Output: 0
Explanation: A single element cannot form a pair.
Input: ([2, 2, 2, 2], 4)
Expected Output: 2
Explanation: Four 2's form two disjoint pairs (2+2 = 4 each).
Input: ([1, 1, 1], 2)
Expected Output: 1
Explanation: Three 1's: one pair (1+1 = 2) is formed, the leftover 1 is unpaired.
Input: ([-1, -2, -3, -4, 3, 1], -3)
Expected Output: 2
Explanation: Pairs (-1,-2) and (-4,1) both sum to -3; -3 and 3 are left unpaired.
Input: ([0, 0, 0, 0, 0], 0)
Expected Output: 2
Explanation: Five 0's with k = 0: 0+0 = 0, so two pairs form and one 0 is left over.
Hints
- The maximum number of disjoint pairs is independent of pairing order, so a greedy single pass suffices — no backtracking is needed.
- Keep a hash map of unused values seen so far. For each value x, look up k - x; if an unused copy exists, consume it and count one operation, otherwise store x.
- Self-complement values (where x == k - x, e.g. x = k/2, or x = 0 with k = 0) just pair up among themselves naturally because the map count is decremented as you match.
- Sorting plus two pointers (one from each end moving toward a target sum) is an O(n log n) alternative with O(1) extra space — useful when memory is tight.