
Problem: “Write a function to swap two numbers in place (without temporary variables).”
We’ll solve it using the arithmetic (+/–) method only.
🔸 TLDR
▪️ Use sum/diff to swap values without a temp variable.
▪️ Add a same-index guard to avoid no-ops.
▪️ Beware of integer overflow when adding.
▪️ In Java, demo via array indices (primitives are pass-by-value).
▪️ In production, a temp var is usually clearer and safer.
🔸 JAVA IMPLEMENTATION (SUM/DIFF)
// Swaps a[i] and a[j] using +/-
static void swapSum(int[] a, int i, int j) {
if (i == j) return; // same slot = nothing to do
a[i] = a[i] + a[j];
a[j] = a[i] - a[j];
a[i] = a[i] - a[j];
}
How it works:
(x + y) - y = x and (x + y) - x = y — we reuse the combined sum to reconstruct each original value.
🔸 EDGE CASES & SAFETY
▪️ Overflow risk: a[i] + a[j] can exceed int range.
▪️ Mitigations:
▪️ Use long[] if values might be large.
▪️ Or validate before adding; or wrap with Math.addExact(a[i], a[j]) and catch ArithmeticException.
▪️ Same index: Guard with if (i == j) return;.
🔸 WHY NOT JUST USE A TEMP?
▪️ Clarity cleverness: A temp variable is self-explanatory and avoids overflow pitfalls.
▪️ Performance: JIT/compilers optimize well—micro-optimizations here rarely matter.
🔸 TAKEAWAYS
▪️ The sum/diff swap is a neat trick for interviews.
▪️ Always consider overflow and same-index cases.
▪️ Prefer readability in real code—temporary variables are fine.
▪️ In Java, demonstrate swaps via array/wrapper (not plain int parameters).
🔸 S
#Java #CodingInterview #Algorithms #CleanCode #ProblemSolving #Backend #DevTips #BitManipulation #SoftwareEngineering