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.
Watch: the ordinary example passes, but the odd inputs (empty, very large) fail. Compare with the fixed version.
- moving now
- being checked
- finished / the result
The checklist
| Case | What often breaks |
|---|---|
| Empty: [], "", null | 0 / 0 division, a[0] being undefined, reduce with no initial value |
| One element | loops starting at 1, two pointers that meet at once |
| Zero and negative | a starting value of 0 for max, % on negatives, if (x) wrongly failing for 0 |
| Very large | overflow to Infinity, IDs beyond 2^53, O(n²) time |
| Duplicates | binary search returning any one of them, a Set dropping data |
| Already sorted or reversed | quick sort at O(n²), a BST turning into a chain |
| Range edges | off-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
What does [].reduce((a, b) => a + b) give in JavaScript?
if (count) { … } is wrong for which value?
Why do the examples in a task rarely find bugs?
0 of 3 answered.