Prompt
Sum all integers within an inclusive range (start to end). Return 0 if start > end.
Solution
This question separates candidates who compute from candidates who derive. The loop answer — accumulate from start to end — is O(n) and correct. The arithmetic series formula — (first + last) × count / 2 — is O(1), and it's the difference between "can write a for loop" and "recognized the math". The Gauss pairing intuition takes one sentence: pair the first and last elements, each pair sums to (start + end), and there are count/2 pairs.
The details that actually get tested:
- Inclusive count is
end - start + 1, notend - start. The fencepost error. rangeSum(1, 5) has five terms, not four. - The guard clause handles the contract's degenerate case (start > end → 0) before the formula runs — otherwise the formula happily returns a negative "sum" for an empty range.
- Negative bounds just work: rangeSum(-2, 2) = 0 because the formula is algebra, not iteration. Worth testing out loud to show the formula's domain is wider than the loop's obvious cases.
- The division by 2 is always exact — (start + end) and count can't both be odd — so no floating-point concern for integer inputs.
The O(1)-vs-O(n) distinction sounds academic until the range is 1 to 10⁹ — the loop takes seconds, the formula takes nanoseconds. Constant-time closed forms beat iteration whenever they exist.
Red flag: end - start as the count — off-by-one on the very first test — or looping when the interviewer's follow-up is obviously "now do it for a billion elements".
Say it: "Arithmetic series: (first + last) times count over two, with count = end − start + 1 inclusive — O(1) instead of an O(n) loop, and the guard covers the empty range."