Spot Hidden Differences Between Two Array Routines
Math & Bit ManipulationModel answerLast updated
Decide whether two array-processing routines behave identically under 32-bit integer rules, find a smallest counterexample if not, and design tests that expose subtle divergences.
You are shown two short routines that each take an integer array A with |A| ≤ 10^5. Both are meant to do the same job. Your task is to decide whether they really behave the same way on every valid input.
The inputs are 32-bit signed integers. The problem statement tells you which arithmetic rule applies: either overflow wraps around modulo 2^32, or overflow is forbidden and counts as undefined behavior.
What you need to deliver
- A verdict: are the routines equivalent for all inputs that satisfy the precondition? Argue it from the semantics, not just from a few runs.
- If they are not equivalent, a concrete counterexample, ideally the smallest one you can find.
- A comparison of their time and space complexity.
- A list of hidden differences you checked for, such as:
- mutation of the caller's array
- stability of ordering or tie-breaking
- overflow or underflow behavior
- integer division and modulo semantics
- A test plan: property-based tests plus targeted edge cases that would support or refute your conclusion.
Illustrative pair to practice on
P(A): s = 0; for i in 1..n-1: s += A[i]; return s # sum of everything after the first element
Q(A): t = 0; for x in A: t += x; return t - A[0] # total minus the first element
Answer for both overflow rules, and explain how the verdict changes.
Hints
Hint 1
Define observable behavior first: the return value, the final contents of the input array, and any exceptions or undefined behavior. Equivalence means all of these match for every valid input.
Hint 2
Walk through a checklist of divergence classes: overflow in intermediate values, truncating versus flooring division, sign of modulo results, in-place versus copying sorts, tie-breaking, empty and single-element arrays, and INT_MIN edge cases.
Hint 3
Wrapping arithmetic is modular, so reordering additions and subtractions never changes the final result. If overflow is forbidden, only the intermediate values matter, so look for an input where one routine's partial sum leaves the 32-bit range and the other's does not.
Hint 4
Testing can refute equivalence but never prove it. Bias random generators toward boundary values, then shrink any failing input to a minimal counterexample.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two routines are equivalent only if, for every input meeting the precondition, they produce the same observable behavior: the same return value, the same final state of any mutable argument, and the same exceptions or undefined behavior. A strong answer has three stages.
- Reason semantically. Reduce each routine to a mathematical function, then check every place where the machine model departs from ordinary math.
- Walk a divergence checklist. Most pairs that look equivalent differ in exactly one category.
- Confirm with differential testing. Run both on edge cases and biased random inputs, and shrink any mismatch.
Divergence checklist
| Class | Typical trap |
|---|---|
| Overflow | A running total or a+b midpoint overflows while the direct form does not. Under "overflow prohibited" this alone breaks equivalence. |
| Integer division | C and Java truncate toward zero, Python // floors. They differ only when operand signs differ and the remainder is nonzero. |
| Modulo | -7 % 3 is -1 in C and 2 in Python. |
| Mutation | In-place sort and a copying sorted return the same values but leave the caller's array different. |
| Stability and ties | Unstable sort, or "first max" versus "last max" index. |
| Empty and singleton | Division by length, indexing A[0], initial value 0 versus negative infinity. |
| Extremes | abs(INT_MIN), -INT_MIN, and INT_MIN / -1 overflow. |
| Complexity | Same outputs but O(n²) versus O(n) matters at n = 10^5. Report it separately as a non-functional difference. |
Worked verdict for the practice pair
P sums A[1..] directly. Q sums everything and subtracts A[0].
- Wrapping 32-bit arithmetic: addition and subtraction mod 2^32 form a ring, so
t - A[0] ≡ Σ A[1:](mod 2^32) regardless of order. The routines are equivalent. - Overflow prohibited: take
A = [2147483647, 1, -1].Pcomputes1 + (-1) = 0and never overflows.Qcomputes2147483647 + 1first, which overflows. The routines are not equivalent, and this array is the counterexample. It is also minimal in the sense that no shorter array triggers the issue (withn = 2,Qoverflows only if the sum itself overflows, and that case does not separate the two cleanly).
The lesson: the algebra is right, but intermediate values can leave the representable range.
Other short examples
- Division:
trunc(sum/n)versussum // nagree whensum ≥ 0orndividessum. The smallest counterexample is[-1, 0]: truncation gives0, flooring gives-1. - Mutation: a median that calls
A.sort()and one that usessorted(A)return the same value. On[2, 1]the caller sees[1, 2]after the first and[2, 1]after the second. If the spec says the input must not change, they differ.
Complexity
- The sum pair are both O(n) time and O(1) extra space.
sorted(A)costs O(n log n) time and O(n) extra space, while in-place sort is O(n log n) time and O(1) to O(log n) extra space depending on the algorithm.- The test harness costs O(T_f + T_g + n) per trial because each run needs a fresh copy. Shrinking by deleting elements and reducing values takes roughly O(n·k) extra runs.
Why the method is sound
- A semantic argument can prove equivalence. Modular arithmetic being a ring means any expression built from
+,-,*is order-independent mod 2^32. - Tests only refute. Bugs cluster at boundaries (sign changes,
INT_MIN/INT_MAX, empty input, ties), so generators biased toward those values find them quickly. - Shrinking converts a random failure into a minimal counterexample, which is the deliverable.
Test plan
Edge cases:
[],[x][INT_MAX],[INT_MIN],[INT_MAX, 1],[INT_MIN, -1],[INT_MAX, 1, -1][-1, 0],[-3, 0]for negative non-divisible sums- all-equal, sorted, reverse-sorted arrays
- alternating extremes
- n = 10^5 for performance
Properties:
- Differential: outputs match and post-call array states match, with exceptions treated as outputs.
- Reference oracle: compare both against an arbitrary-precision model of the spec, then apply wrap or check semantics.
- Metamorphic: permuting the input must not change a sum; a sort's output must be a sorted permutation, and a stable sort keeps equal keys in original order.
- Non-mutation: the input after the call equals the input before it.
Sketch of a harness
INT_MIN, INT_MAX = -2**31, 2**31 - 1
class Overflow(Exception): pass
def wrap32(x): return (x + 2**31) % 2**32 - 2**31
def checked(x):
if x < INT_MIN or x > INT_MAX:
raise Overflow(x)
return x
def observe(f, A):
arg = list(A)
try:
out = ("ok", f(arg))
except Exception as e:
out = ("err", type(e).__name__)
return out, arg
def differs(f, g, A, check_mutation=True):
(of, af), (og, ag) = observe(f, A), observe(g, A)
return of != og or (check_mutation and af != ag)
def shrink(f, g, A):
changed = True
while changed:
changed = False
for i in range(len(A)):
cand = A[:i] + A[i+1:]
if differs(f, g, cand):
A, changed = cand, True
break
return A
Generate inputs from a pool weighted toward 0, ±1, ±2, INT_MAX, INT_MIN and their neighbors, run differs, and shrink on failure.
Common mistakes
- Declaring equivalence from algebra alone and ignoring intermediate overflow.
- Forgetting that "overflow prohibited" turns a mathematically harmless reordering into undefined behavior.
- Comparing only return values and missing mutation.
- Testing only random small numbers, which almost never hits
INT_MAXorINT_MIN. - Ignoring empty input, where one routine may index
A[0]and the other may not.