Data Structures & Algorithms / Module 10: Correctness and reviewing AI code

Topic 10.2

Edge cases

Empty, one, zero, negative, very large: a checklist of the inputs that break code.

9 min · beginner

Watch: the ordinary example passes, but the odd inputs (empty, very large) fail. Compare with the fixed version.

[4,8,6][5][ ][-2,2][big,big]
  • moving now
  • being checked
  • finished / the result
Step 1 of 7

average(a) = sum / length. It passes the usual example. Now try the awkward inputs.

The example in a task is almost always the easy case. Bugs live at the edges: empty, one element, negative, and very large.

The checklist

CaseWhat often breaks
Empty: [], "", null0 / 0 division, a[0] being undefined, reduce with no initial value
One elementloops starting at 1, two pointers that meet at once
Zero and negativea starting value of 0 for max, % on negatives, if (x) wrongly failing for 0
Very largeoverflow to Infinity, IDs beyond 2^53, O(n²) time
Duplicatesbinary search returning any one of them, a Set dropping data
Already sorted or reversedquick sort at O(n²), a BST turning into a chain
Range edgesoff-by-one: < or <=, the first and last element

Example: an average

sum / length looks impossible to get wrong. But an empty list gives 0 / 0 = NaN, with no error. That NaN then quietly shows up on a dashboard as "NaN%". Two very large numbers push the sum past the limit into Infinity, though their average is perfectly ordinary. Choose "fixed version" in the figure to see everything pass.

Code, for programmersAn average that handles the edges
function average(a) {
  if (a.length === 0) return null;     // decide what 'no data' means, out loud
  let mean = 0;
  a.forEach((x, i) => {
    mean += (x - mean) / (i + 1);      // running mean: never builds a huge total
  });
  return mean;
}

// and pin the edges down as tests
test.each([
  [[4, 8, 6], 6],
  [[5], 5],
  [[], null],
  [[-2, 2], 0],
])("average(%j) = %j", (input, want) => expect(average(input)).toBe(want));

Quiz

  1. What does [].reduce((a, b) => a + b) give in JavaScript?

  2. if (count) { … } is wrong for which value?

  3. Why do the examples in a task rarely find bugs?

0 of 3 answered.