Minimum Absolute Array Sum

Easy · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

Given a non-empty integer list A, you may optionally flip the sign of a single entry (replacing A[i] with -A[i] at zero or one index i).

Implement minAbsoluteSum(A) to compute the smallest possible magnitude |sum| of the array's total sum after performing zero or one sign flip.

Examples

Example 1

  • Input: A = [2, 5, 1, 6]
  • Output: 2
  • Explanation: Without any flip, the entries sum to 14. Flipping 6 to -6 produces [2, 5, 1, -6] with total 2, giving |2| = 2.

Example 2

  • Input: A = [-6, 2, -4, 1]
  • Output: 1
  • Explanation: The untouched sum is -7. Flipping -4 to +4 changes the array to [-6, 2, 4, 1], whose sum is 1 (|1| = 1).

Example 3

  • Input: A = [6, -5, 2, -4]
  • Output: 1
  • Explanation: Leaving every number as-is gives a sum of -1 (|-1| = 1). Flipping any single element yields magnitudes 13, 9, 5, or 7, none of which beat 1.

Example 4

  • Input: A = [20, -25, 8, -2, -12]
  • Output: 7
  • Explanation: The initial sum is -11. Flipping -25 overshoots zero to +39, whereas flipping -2 to +2 moves the sum to -7, whose magnitude 7 is minimal.

Constraints

  • 1 <= len(A) <= 100,000
  • -1,000 <= A[i] <= 1,000

Step-by-step walkthrough

  1. Understand the goal and the "at most one" rule

    We are given an integer array A of length N and want the sum of its elements to land as close to 0 as possible — meaning we want to minimize abs(sum), the distance of the sum from 0 on the number line.

    We may multiply at most one element by -1. "At most one" gives us two kinds of choices:

    • Flip 0 elements: leave every element untouched and keep the original array sum.
    • Flip 1 element: pick a single index i, replace A[i] with -A[i], and take the new sum.

    Keeping the untouched sum as a candidate is essential. In Example 3 (A = [6, -5, 2, -4]), the original sum is -1 (abs(-1) = 1), and flipping any element pushes the sum further away from 0.

    # Baseline before flipping anything ("at most one" includes zero flips)
    total_sum = sum(A)
    min_abs_sum = abs(total_sum)
    
  2. Why re-summing from scratch is too slow

    A literal brute-force loop tries every index i, flips A[i], calls sum(A) across all N elements, and flips A[i] back.

    Because N can be up to 100,000, running an O(N) sum(A) inside an O(N) loop performs up to 100,000 * 100,000 = 10^10 additions, which is far too slow. Notice why it wastes work: when we flip one element x, the other N - 1 elements do not change at all.

  3. Key insight: flipping `x` shifts the total sum by `-2 * x`

    Suppose we already know total_sum = sum(A). What happens to that sum when we replace one element x with -x?

    1. First, subtract the old +x that was originally included in total_sum: total_sum - x.
    2. Next, add the newly negated value -x: (total_sum - x) + (-x) = total_sum - 2 * x.

    Notice the factor of 2: flipping 6 into -6 does not lower the sum by 6 — it lowers the sum by 12! And because -2 * (-4) = +8, the exact same formula works whether x is positive, negative, or zero:

    A = [-6, 2, -4, 1]   ->   total_sum = -7
    No flip:        sum = -7                  -> |-7|  = 7
    Flip x = -6:    sum = -7 - 2*(-6) = +5    -> |+5|  = 5
    Flip x =  2:    sum = -7 - 2*( 2) = -11   -> |-11| = 11
    Flip x = -4:    sum = -7 - 2*(-4) = +1    -> |+1|  = 1  <-- minimum!
    Flip x =  1:    sum = -7 - 2*( 1) = -9    -> |-9|  = 9
    
  4. Watch out for the "flip the biggest number" trap

    It is tempting to test only max(A) and min(A), guessing that the largest element helps the most. That shortcut fails whenever a large element overshoots zero!

    Look at Example 4 (A = [20, -25, 8, -2, -12]), where total_sum = -11: - Flipping the most negative element -25 jumps the sum all the way to -11 - 2 * (-25) = +39 (|39| = 39). - Flipping the small -2 nudges the sum to -11 - 2 * (-2) = -7 (|-7| = 7), which is optimal.

    Because total_sum - 2 * x takes O(1) arithmetic per element, we never need to guess — we simply check every x in A:

    for x in A:
        flipped_sum = total_sum - 2 * x
        candidate_abs = abs(flipped_sum)
        if candidate_abs < min_abs_sum:
            min_abs_sum = candidate_abs
    
  5. Complete solution

    Combining the zero-flip baseline with the single-pass scan gives the complete O(N) solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def minAbsoluteSum(A: List[int]) -> int:
        # Phase 1: Compute the baseline sum if we negate zero elements ("at most one").
        total_sum = sum(A)
    
        # min_abs_sum: smallest |sum| seen so far, initialized to the 0-flip baseline.
        min_abs_sum = abs(total_sum)
    
        # Phase 2: Try negating each element x one at a time.
        # Replacing +x with -x removes x once and adds -x once, shifting total_sum by -2 * x.
        for x in A:
            flipped_sum = total_sum - 2 * x
            candidate_abs = abs(flipped_sum)
            if candidate_abs < min_abs_sum:
                min_abs_sum = candidate_abs
    
        return min_abs_sum
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture a number-line balance beam where positive numbers pull the pointer to the right and negative numbers pull it to the left. Before we touch anything, all elements together place the pointer at total_sum. When we pick one number x and multiply it by -1, we take x off its original side (-x) and place it on the opposite side (-x again), shifting the pointer to total_sum - 2 * x. Our goal is simply to check the starting position and each of the N single-flip positions, keeping whichever lands closest to 0.

Why do the obvious alternatives fall short? Re-summing the whole array for each of the N flips repeats almost the exact same addition N times, costing O(N^2) time — around 10^10 operations when N = 100,000. On the other hand, greedily flipping only the largest positive or negative element can overshoot 0 badly (for example, when total_sum = 7 and A = [100, -95, 2], flipping 100 lands at -193, whereas flipping 2 lands at 3). Precomputing total_sum once gives us the exact result of every flip in O(1) arithmetic without guessing.

Let's walk through Example 1 (A = [2, 5, 1, 6]):

Step 1: Compute total_sum = 2 + 5 + 1 + 6 = 14
        Initialize min_abs_sum = |14| = 14 (flipping 0 elements)

Step 2: Test flipping each element x using |total_sum - 2 * x|:
  x = 2  ->  |14 - 2 * 2| = |10| = 10  ->  min_abs_sum = 10
  x = 5  ->  |14 - 2 * 5| = |4|  = 4   ->  min_abs_sum = 4
  x = 1  ->  |14 - 2 * 1| = |12| = 12  ->  min_abs_sum stays 4
  x = 6  ->  |14 - 2 * 6| = |2|  = 2   ->  min_abs_sum = 2

Return 2.

Complexity

  • Time: O(N), where N is the length of A. We scan the N elements once to compute sum(A) and scan them a second time doing O(1) subtraction and abs(...) work per element.
  • Space: O(1) auxiliary space (extra memory used beyond the input array itself). We only keep a handful of integer variables (total_sum, min_abs_sum, flipped_sum, candidate_abs) regardless of how large N grows.

Edge cases

  • No flip is optimal (A = [6, -5, 2, -4]): Starting min_abs_sum at abs(total_sum) before the loop ensures we never force a harmful flip when the untouched sum is already closest to 0.
  • Single-element array (A = [7] or A = [-9]): abs(total_sum) and abs(total_sum - 2 * x) = abs(-total_sum) both equal abs(A[0]), returning 7 or 9 cleanly.
  • Sum already 0 (A = [10, -4, -6]): min_abs_sum starts at 0, the theoretical minimum of any absolute value, and stays 0.
  • Negative elements (x < 0): Subtracting 2 * x when x is negative automatically adds 2 * |x| (for example, -7 - 2 * (-4) = +1), so no separate if x < 0 branch is needed.

Common mistakes

  • Writing total_sum - x instead of total_sum - 2 * x: Subtracting x once only deletes x from the array (setting it to 0) rather than replacing +x with -x.
  • Initializing min_abs_sum = float("inf") and only checking 1-element flips: That solves "flip exactly one element" and fails inputs like [10, -9] where flipping zero elements gives 1 while flipping either element gives 19.
  • Only testing max(A) and min(A): We want 2 * x close to total_sum, meaning x should be as close to total_sum / 2 as possible — which is often a small middle element rather than an extreme one.

Follow-up questions

  • How would your solution change if you were required to negate strictly one element rather than at most one? Initialize min_abs_sum to abs(total_sum - 2 * A[0]) (since len(A) >= 1) instead of abs(total_sum), and then scan A. Every candidate checked now corresponds to negating an actual index, keeping O(N) time and O(1) auxiliary space.
  • How could you minimize the absolute sum if you were allowed to negate up to two distinct elements? Negating two distinct indices i != j shifts the sum to total_sum - 2 * (A[i] + A[j]), so we want a pair sum A[i] + A[j] as close to total_sum / 2 as possible. Sort a copy of A in O(N log N) time and sweep two pointers (one index starting at the left end and one at the right end, advancing inward depending on whether A[left] + A[right] is below or above total_sum / 2) in O(N) time, taking the minimum across the 0-flip, 1-flip, and 2-flip candidates.
  • What approach would you use if any subset of elements could be negated? Because every element can independently take a + or - sign, replace each entry with its magnitude m = abs(x) and partition those magnitudes into two groups whose sums are as close as possible. For moderate total magnitude S = sum(abs(x) for x in A), 0/1 subset-sum dynamic programming (building a boolean table of reachable subset sums as elements are added one by one) runs in O(N * S) time; when individual magnitudes are bounded by K (|A[i]| <= 1,000), balanced dynamic programming keeping intermediate differences within [-K, K] solves it in O(N * K) time.

Follow-up questions

Similar questions

More Google interview questions

All 1125 Google questions →