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. Flipping6to-6produces[2, 5, 1, -6]with total2, giving|2| = 2.
Example 2
- Input:
A = [-6, 2, -4, 1] - Output:
1 - Explanation: The untouched sum is
-7. Flipping-4to+4changes the array to[-6, 2, 4, 1], whose sum is1(|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 magnitudes13,9,5, or7, none of which beat1.
Example 4
- Input:
A = [20, -25, 8, -2, -12] - Output:
7 - Explanation: The initial sum is
-11. Flipping-25overshoots zero to+39, whereas flipping-2to+2moves the sum to-7, whose magnitude7is minimal.
Constraints
1 <= len(A) <= 100,000-1,000 <= A[i] <= 1,000
Step-by-step walkthrough
Understand the goal and the "at most one" rule
We are given an integer array
Aof lengthNand want the sum of its elements to land as close to0as possible — meaning we want to minimizeabs(sum), the distance of the sum from0on 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, replaceA[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 from0.# Baseline before flipping anything ("at most one" includes zero flips) total_sum = sum(A) min_abs_sum = abs(total_sum)Why re-summing from scratch is too slow
A literal brute-force loop tries every index
i, flipsA[i], callssum(A)across allNelements, and flipsA[i]back.Because
Ncan be up to100,000, running anO(N)sum(A)inside anO(N)loop performs up to100,000 * 100,000 = 10^10additions, which is far too slow. Notice why it wastes work: when we flip one elementx, the otherN - 1elements do not change at all.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 elementxwith-x?- First, subtract the old
+xthat was originally included intotal_sum:total_sum - x. - Next, add the newly negated value
-x:(total_sum - x) + (-x) = total_sum - 2 * x.
Notice the factor of
2: flipping6into-6does not lower the sum by6— it lowers the sum by12! And because-2 * (-4) = +8, the exact same formula works whetherxis 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- First, subtract the old
Watch out for the "flip the biggest number" trap
It is tempting to test only
max(A)andmin(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]), wheretotal_sum = -11: - Flipping the most negative element-25jumps the sum all the way to-11 - 2 * (-25) = +39(|39| = 39). - Flipping the small-2nudges the sum to-11 - 2 * (-2) = -7(|-7| = 7), which is optimal.Because
total_sum - 2 * xtakesO(1)arithmetic per element, we never need to guess — we simply check everyxinA: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_absComplete 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), whereNis the length ofA. We scan theNelements once to computesum(A)and scan them a second time doingO(1)subtraction andabs(...)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 largeNgrows.
Edge cases
- No flip is optimal (
A = [6, -5, 2, -4]): Startingmin_abs_sumatabs(total_sum)before the loop ensures we never force a harmful flip when the untouched sum is already closest to0. - Single-element array (
A = [7]orA = [-9]):abs(total_sum)andabs(total_sum - 2 * x) = abs(-total_sum)both equalabs(A[0]), returning7or9cleanly. - Sum already
0(A = [10, -4, -6]):min_abs_sumstarts at0, the theoretical minimum of any absolute value, and stays0. - Negative elements (
x < 0): Subtracting2 * xwhenxis negative automatically adds2 * |x|(for example,-7 - 2 * (-4) = +1), so no separateif x < 0branch is needed.
Common mistakes
- Writing
total_sum - xinstead oftotal_sum - 2 * x: Subtractingxonce only deletesxfrom the array (setting it to0) rather than replacing+xwith-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 gives1while flipping either element gives19. - Only testing
max(A)andmin(A): We want2 * xclose tototal_sum, meaningxshould be as close tototal_sum / 2as 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_sumtoabs(total_sum - 2 * A[0])(sincelen(A) >= 1) instead ofabs(total_sum), and then scanA. Every candidate checked now corresponds to negating an actual index, keepingO(N)time andO(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 != jshifts the sum tototal_sum - 2 * (A[i] + A[j]), so we want a pair sumA[i] + A[j]as close tototal_sum / 2as possible. Sort a copy ofAinO(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 whetherA[left] + A[right]is below or abovetotal_sum / 2) inO(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 magnitudem = abs(x)and partition those magnitudes into two groups whose sums are as close as possible. For moderate total magnitudeS = 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 inO(N * S)time; when individual magnitudes are bounded byK(|A[i]| <= 1,000), balanced dynamic programming keeping intermediate differences within[-K, K]solves it inO(N * K)time.
Follow-up questions
- How would your solution change if you were required to negate strictly one element rather than at most one?
- How could you minimize the absolute sum if you were allowed to negate up to two distinct elements?
- What approach would you use if any subset of elements could be negated?
Similar questions
- Minimum Insertions for Target Subsequence
- Nightly Chapter Reading
- Tally Exam Score Tiers
- Smallest Vehicle Fleet for Booking Intervals
- Fewest Clear Cells Across an Eight-Way Grid
- Linear Track Robot Collisions
More Google interview questions
- Smallest Vehicle Fleet for Booking Intervals Medium
- Nightly Chapter Reading Easy
- Tally Exam Score Tiers Easy Pro
- Minimum Event Chairs Easy Pro
- Dining Waitlist Manager Hard Pro
- Four-Digit PINs with Target Digit Sum Easy Pro
- Filesystem Subtree Byte Usage Medium Pro
- Token Row Score Easy Pro
- Highest-Sum Subarray with Matching Ends Medium Pro
- Navigating an Engineering Project With Open-Ended Requirements Medium Pro