Magicsheet logo

Sum of Mutated Array Closest to Target

Medium
25%
Updated 8/1/2025

Sum of Mutated Array Closest to Target

What is this problem about?

Given an integer array arr and a target value target, you need to find an integer value such that when you replace all integers in the array greater than value with value, the sum of the resulting array is as close to target as possible. If there are multiple such integers, return the minimum one.

Why is this asked in interviews?

This is a high-quality Medium problem frequently asked by Google and Bloomberg. it tests the ability to recognize a monotonic property (as value increases, the sum increases) which allows for Binary Search. It also evaluates a candidate's attention to detail, specifically in handling the "closest" condition where you must compare two potential candidates (one slightly below and one slightly above the ideal sum).

Algorithmic pattern used

The pattern is "Binary Search on the Result Space." The possible range for value is between 0 and the maximum element in the array.

  1. Binary Search: Pick a middle value.
  2. Calculation: Calculate the "mutated sum" for that value.
  3. Adjustment: If the sum is less than the target, search the higher range. If it's more, search the lower range. Finally, check the two closest integers found by the binary search to see which one yields a sum with a smaller absolute difference from the target.

Example explanation

arr = [4, 9, 3], target = 10.

  • Try value = 3: Array becomes [3, 3, 3]. Sum = 9. Difference = |9 - 10| = 1.
  • Try value = 4: Array becomes [4, 4, 3]. Sum = 11. Difference = |11 - 10| = 1. Since both have the same difference, we return the smaller value, which is 3.

Common mistakes candidates make

  1. Linear Search: Trying to iterate through every possible value from 0 to max(arr). This is O(MaxVal * N), which is too slow.
  2. Tie-breaking: Forgetting to return the minimum value if two values give the same distance to the target.
  3. Sum Calculation: Not optimizing the sum calculation. Sorting the array and using prefix sums allows you to calculate the mutated sum for a given value in O(log N) instead of O(N).

Interview preparation tip

Binary search isn't just for searching elements in an array; it's also for finding an optimal value in a defined range. If a function is monotonic (always increasing or always decreasing), you can use binary search to find a target value.

Similar Questions