Lesson 1.3
Hunt edge cases
7 min · 7 steps
Step 1 of 7 · Explanation
An edge case is an input at the border of the rules. Check this list every time: empty, one item, duplicates or ties, negatives, max size.
Example problem: "Return the second largest distinct number, or -1 if there isn't one." For
[4, 9, 9, 2], the answer is 4, not 9. The second 9 is a duplicate, so it can't count as the second largest.Step 2 of 7 · Pick the approach
Constraints:
1 ≤ nums.length ≤ 10⁵and-10⁹ ≤ nums[i] ≤ 10⁹.
Which input can never appear in a test?[][-3][7, 7, 7]- An array of 100
Step 3 of 7 · Predict the result
This code returns the second largest distinct number, or -1 if there isn't one. What does it return for
[5, 5]?function solution(nums) { let first = -Infinity let second = -Infinity for (let i = 0; i < nums.length; i++) { const n = nums[i] if (n > first) { second = first first = n } else if (n > second && n < first) { second = n } } return second === -Infinity ? -1 : second}-150
Step 4 of 7 · Find the bug
This code should return the second largest distinct number, or -1 if there isn't one. It passes
[4, 9, 2]but fails the hidden test[9, 9](expected -1). Tap the wrong line.function solution(nums) { let first = -Infinity let second = -Infinity for (let i = 0; i < nums.length; i++) { const n = nums[i] if (n > first) { second = first first = n } else if (n > second) { second = n } } return second === -Infinity ? -1 : second}Step 5 of 7 · Predict the result
This code returns the second largest distinct number, or -1 if there isn't one. What does it return for
[-3, -7]?function solution(nums) { let first = -Infinity let second = -Infinity for (let i = 0; i < nums.length; i++) { const n = nums[i] if (n > first) { second = first first = n } else if (n > second && n < first) { second = n } } return second === -Infinity ? -1 : second}-7-1-3
Step 6 of 7 · Write the code
solution(nums)Return the smallest number in
nums. Ifnumsis empty, returnnull.
Constraints:0 ≤ nums.length ≤ 100,-1000 ≤ nums[i] ≤ 1000.function solution(nums) { // [3, 1, 2] -> 1 // [] -> null }Step 7 of 7 · Recap
- Edge case checklist: empty, one item, duplicates, negatives, max size.
- The constraints tell you which ones can happen and which can't.
- A starting value of
-Infinityornums[0]is safe for negatives. A starting value of 0 isn't.