KatInterview

Spot Hidden Differences Between Two Array Routines

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationprogram-equivalenceinteger-overflowproperty-based-testing

Last 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

  1. A verdict: are the routines equivalent for all inputs that satisfy the precondition? Argue it from the semantics, not just from a few runs.
  2. If they are not equivalent, a concrete counterexample, ideally the smallest one you can find.
  3. A comparison of their time and space complexity.
  4. 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
  5. 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.