← MathWorks Interview Insights
Sorted the array first, then ran two pointers from each end to check if every pair hit the same target.
First, sort the array and check if pairing the smallest with the largest yields a constant sum. If so, compute the sum of products of these pairs; otherwise, return -1. This approach ensures O(n log n) time and O(1) extra space.
Pro tip: After sorting, verify the constant sum condition by checking only the first and last pair; if they match, all other pairs will automatically match due to the sorted order. This avoids unnecessary checks and demonstrates efficient reasoning.
Sort the array in ascending order to easily pair smallest with largest elements.
Compute the sum of the first and last elements as the target sum for all pairs.
Iterate through the array from both ends, checking if each pair sums to the target. If any pair does not, return -1.
If all pairs are valid, calculate the product of each pair and sum them up.
Return the computed sum if valid, otherwise -1.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.