← MathWorks Interview Insights
I went for the hash map approach first since it felt cleaner to explain.
Start by clarifying the problem: we need to maximize the number of disjoint pairs that sum to T. Then present both solutions: the hash map approach that counts frequencies and greedily pairs complements, and the sorting with two pointers approach that pairs smallest with largest. Prove correctness by arguing that any valid pairing can be transformed into the greedy pairing without reducing the count, and discuss edge cases and trade-offs.
Pro tip: Emphasize that the hash map solution is O(n) time but O(n) space, while sorting is O(n log n) time but O(1) extra space (if in-place). Mention that the greedy pairing is optimal because each element can be used at most once, so maximizing pairs is equivalent to finding a maximum matching in a graph where edges connect elements summing to T, and the greedy strategy achieves this maximum.
Restate the problem: given an array and target T, repeatedly remove two elements that sum to T. Ask if elements can be reused (no), if order matters (no), and if we need to return the pairs or just the count. Discuss potential edge cases like empty array, no valid pairs, and large values causing integer overflow.
Use a frequency map to count occurrences of each number. Iterate through the array; for each number x, check if T - x exists in the map with positive count. If so, decrement counts and increment pair count. Handle the case where x == T - x by ensuring at least two occurrences. This greedy pairing is optimal because each element can be used at most once.
Sort the array. Use two pointers: left at start, right at end. If sum == T, increment pair count and move both pointers inward. If sum < T, move left right; if sum > T, move right left. This works because sorting allows us to efficiently find pairs that sum to T.
For hash map: argue that any valid pairing can be rearranged so that each element is paired with its complement, and the greedy algorithm finds the maximum number of such pairs. For two pointers: use the fact that if the smallest element cannot pair with the largest, it cannot pair with any other element (since all others are smaller), so we can safely discard it. Similarly for the largest.
Cover duplicates (e.g., [2,2,2,2] with T=4), negative numbers (e.g., [-1,1,2,3] with T=2), and large values (overflow when summing). Compare trade-offs: hash map is faster but uses extra space; sorting is slower but uses less space and is simpler to implement without extra data structures.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.