← MathWorks Interview Insights

MathWorks·Software Engineer·Technical Phone Screen·Intermediate

Intermediate
May 2026

Summary

MathWorks SET interview with an array pairing problem that sounds deceptively clean but has a few gotchas if you're not careful about how you set up the target sum.

Questions Asked (1)

Q1

Given an even-length array, pair all elements so every pair has the same sum. If a valid pairing exists, return the sum of the products of all pairs. Otherwise return -1.

Algorithms & Data Structures
Author's notes

Sorting first makes this way cleaner.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Sort the array and pair the smallest with the largest, checking if every pair sums to the same value. If all pairs match, compute the sum of products; otherwise return -1.

Pro tip: Mention that sorting is O(n log n) and that the greedy pairing is optimal because any valid pairing must pair extremes together. Also, clarify edge cases like negative numbers and duplicates.

1. Understand the problem

Restate the problem: given an even-length array, determine if it can be partitioned into pairs with identical sums. If yes, return the sum of the products of each pair; else return -1.

2. Sort the array

Sort the array in ascending order. This allows a two-pointer approach to check pair sums efficiently.

3. Check pair sums

Pair the first and last elements, the second and second-last, etc. Compute the sum of the first pair and verify that all other pairs have the same sum. If any pair differs, return -1.

4. Compute sum of products

If all pairs have the same sum, iterate through the pairs again to compute the product of each pair and accumulate the total sum. Return this sum.

5. Handle edge cases

Consider arrays with negative numbers, zeros, or duplicates. Ensure the algorithm works correctly for these cases. Also, discuss time and space complexity.

Key Points to Mention

  • Sorting the array is key to efficiently pairing smallest with largest.
  • The greedy pairing (smallest with largest) is necessary for a valid pairing if one exists.
  • Time complexity: O(n log n) due to sorting, and O(n) for the checks.
  • Space complexity: O(1) extra space if sorting in place, or O(n) if using additional arrays.
  • Edge cases: negative numbers, zeros, duplicate values, and arrays with only two elements.
  • If the array length is odd, return -1 immediately (though problem states even length).

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.