Lesson 5 of 27Read before you code
Edge Cases from Constraints
Read each constraint line as a list of edge cases, and run a standard checklist before you call a solution done.
Most solutions that fail the hidden tests are not slow and not wrong in their main idea. They crash on an empty list, return the wrong thing for a single element, or overflow on large values. The good news is that the problem usually tells you which of these will be tested. Every constraint line is a list of edge cases in disguise.
Each constraint line is a test plan
A constraint gives a range. The test authors almost always test both ends of that range. So read each line and ask: "what is the smallest, the largest, and the strangest input this line allows?"
| Constraint line | Edge cases it promises |
|---|---|
0 <= nums.length <= 10^5 | [] is a real test. Also the largest size, for speed. |
1 <= nums.length | No empty input, but one element will be tested. |
-10^9 <= nums[i] <= 10^9 | Negatives, zero, and sums near 10^14 (overflow in 32-bit languages). |
1 <= k <= nums.length | k = 1 and k = n, the whole array. |
| no "distinct" promise | Duplicates, and an array where every value is the same. |
s may contain spaces and punctuation | " ", "a.", a string with no letters at all. |
0 <= edges.length | A graph with no edges: every node is its own component. |
edges may contain cycles | A cycle, including a self-loop if not ruled out. |
1 <= m, n <= 300 (grid) | A 1 x 1 grid, a single row, a single column. |
And the reverse: whatever a constraint rules out, you can stop worrying about. If it says 1 <= nums.length, do not spend time on the empty case. If it says the values are distinct, skip the duplicate logic.
Match the constraint line to the edge case it most strongly suggests.
The standard checklist
When the constraints are vague (or an interviewer gives none), run this list. Not every item applies to every problem; the habit is to ask each one.
- Empty:
[],"", no nodes, no intervals. - One element: a single number, one character, a one-node tree.
- Two elements: the smallest case where pairs, swaps, and neighbours exist.
- All the same:
[5, 5, 5, 5]. Breaks "strictly greater" logic and duplicate skipping. - Duplicates: equal values at different positions.
- Negatives and zero: breaks sliding windows on sums, product logic, "largest is last after sorting".
- Overflow: the largest values added or multiplied together.
- Already sorted / reverse sorted: the worst case for naive quicksort, the best or worst case for greedy scans.
- No valid answer: return
-1,0,[], orfalseas the prompt says. - Graphs: cycles and disconnected parts: a DFS without a
visitedset loops forever on a cycle, and a single BFS from node 0 misses a second component. - The maximum size: for speed, and for recursion depth.
Negatives: the case people forget
Here is a tempting solution to "largest product of any two numbers": sort, and multiply the two biggest. Step through it with negatives.
Sorted input with two negatives. The constraint said -10^4 <= nums[i] <= 10^4, so negatives were promised.
What does the tempting version print?
nums = sorted([-10, -9, 1, 2]) print(nums[-1] * nums[-2])
Duplicates and all-equal input
Duplicates break code that assumes values are unique: a map from value to index silently overwrites, a "strictly greater" comparison never fires, and binary search for "first occurrence" returns any one of the equal values. An all-equal array is the extreme version, and it is cheap to test. A close cousin is a value that pairs with itself: in Two Sum, a number equal to half the target.
value → index first, then for each i returns [i, seen[target - nums[i]]] if that key exists. What does it return for nums = [3, 2, 4], target = 6?Put the edge-case routine in order.
- Tap the steps below in the right order.
1 <= prices.length <= 10^5, 0 <= prices[i] <= 10^4. Which edge cases are worth testing? (Pick all that apply.)None picked yet
Overflow and precision
The value ranges in the constraints tell you whether arithmetic is safe. Each language fails differently.
- Java, C++, Go:
intis 32 bits, so anything past about 2.1 · 10^9 wraps around silently. Sums of 10^5 values up to 10^9 need a 64-bitlong. The classic hidden bug ismid = (lo + hi) / 2overflowing, which is why you seelo + (hi - lo) / 2. - Python: integers never overflow. Floats still have about 15 to 17 significant digits, and
/always returns a float, so use//for integer division and be aware that it floors toward negative infinity (-7 // 2is-4). - JavaScript: every
numberis a 64-bit float, exact only up toNumber.MAX_SAFE_INTEGER(2^53 − 1, about 9 · 10^15). Beyond that, integers silently round. The sneaky case is "return the answer modulo 10^9 + 7": the product of two values near 10^9 is about 10^18, which is already rounded before the%runs. UseBigIntfor the multiply, or split the multiplication. - Floats in any language:
0.1 + 0.2is not exactly0.3. Compare with a tolerance, or keep values as integers (cents, not dollars) when the problem allows.
Press Run (⌘ Enter) to see what happens.Look at the modular product line. It prints a plausible-looking wrong number, which is exactly why this bug survives small tests. Python's 999999999 * 999999999 % 1000000007 gives the correct 64.
What does this print in JavaScript?
console.log(2 ** 53 === 2 ** 53 + 1);
Empty versus null in typed languages
In Python on LeetCode, "empty" usually means [] or None and both are easy to check. In TypeScript, Java and C#, they are different things, and the signature tells you which ones you can receive.
- A tree or linked-list problem typed as
root: TreeNode | nullwill be tested withnull. That is the empty tree, not an error. - An array parameter typed
number[]can be[], but on most platforms is nevernullunless the type says so. Do not litter the code with null checks the type rules out. undefinedin JavaScript appears when you read past the end of an array (nums[nums.length]) or a missing map key. That is not an exception: it flows into arithmetic and becomesNaN. Treat anyNaNin your output as an index-past-the-end bug.- Strings:
""is a valid string with length 0. Checks.length === 0(ornot sin Python) rather than relying on later code to handle it.
In an interview, say which you are handling: "If root is null I return 0. The array is typed non-null, so I only check for empty."
Cycles, self-loops and parallel edges
The checklist mentions cycles. Graph inputs given as edge lists hide three more specific cases that constraint lines rarely rule out:
- Self-loop
[u, u]: a node pointing to itself. It is a cycle of length 1. Union-find detects it immediately (find(u) == find(u)), but a DFS cycle check that ignores the parent can miss or mishandle it. - Parallel edges
[u, v]twice: in an undirected graph this is a cycle of length 2. The common "skip the parent" trick in undirected DFS skips both copies and misses it. Skip the parent edge, by edge id, not the parent node. - Disconnected nodes that appear in
nbut in no edge: they still count as components, so loop overrange(n), not over the keys of your adjacency dict.
If the problem says "a valid tree" or "no duplicate edges", those cases are ruled out. If it is silent, ask, or handle them.
n = 2, edges = [[0, 1], [0, 1]]. An undirected DFS skips the neighbour equal to the parent node and reports 'no cycle'. Is the graph a tree?Very deep input
The recursion-depth quiz above showed the symptom. Here is the fix, and why the usual hopes do not work.
- Tail recursion does not save you. Neither CPython nor Node optimises tail calls, so a recursive call in tail position still uses a stack frame.
- Raising the limit is a gamble.
sys.setrecursionlimit(10**6)lets Python go deeper, but each frame also uses the C stack, and the process can crash with a segmentation fault instead of a clean error. It sometimes works on judges, but say it is a workaround. - JavaScript has no setting at all. The stack size depends on the engine and frame size, typically in the low tens of thousands of frames, so a path of 10^5 nodes overflows.
- The reliable fix is an explicit stack. For DFS that is a few lines. For tree traversals with "after children" work (post-order), push a marker or a
(node, visited)pair.
Press Run (⌘ Enter) to see what happens.Which inputs are deep? A linked list of length n, a tree built from sorted input (a "stick"), a grid flood fill on a snake-shaped path, and any recursion over n itself, such as top-down DP with n up to 10^5. When the constraint says 10^5 and your solution recurses once per element, convert it before you submit.
Unicode and emoji in strings
If the problem does not say "lowercase English letters", the string can contain anything, and "character" becomes ambiguous.
- JavaScript strings are UTF-16.
lengthcounts 16-bit units. Most emoji and many rare symbols are two units (a surrogate pair), so"a\u{1F600}b".lengthis 4, not 3.s.split("")cuts pairs in half, so reversing that way produces broken characters. The spread[...s]andArray.from(s)iterate by code point instead. - Python strings are code points.
lenand slicing never split a code point, so a single emoji has length 1. But a combining accent or a flag is several code points, so reversing can still separate an accent from its letter. - What a reader calls one character is a grapheme cluster. Counting those needs
Intl.Segmenterin JavaScript or a third-party library in Python. Interviews almost never want this. Ask, and usually you can assume ASCII.
The JavaScript block above showed the length difference. When Unicode is in scope, add one string with an accent and one with an emoji to the small, crowded test inputs from Testing Your Own Solution.
Practice
List the edge cases from these constraints before you code, then make sure your solution handles each one.
Best Time to Buy and Sell Stock
prices[i] is a stock's price on day i. You may buy once and then sell once on a later day. Return the largest profit you can make, or 0 if no trade makes money.
prices = [7, 1, 5, 3, 6, 4] → 5 (buy at 1, sell at 6)
prices = [7, 6, 4, 3, 1] → 0 (prices only fall)
prices = [2, 4, 1] → 2 (buy at 2, sell at 4)Constraints
1 <= prices.length <= 10^50 <= prices[i] <= 10^4
- edge case
- An input at the boundary of what the constraints allow: empty, one element, the maximum size, the extreme values.
- both ends of a range
- Test authors test the smallest and largest value of every constraint, so you should too.
- ruled-out case
- Something a constraint forbids (empty when length ≥ 1, negatives when values ≥ 0). You do not need to handle it.
- recursion depth
- How many calls are nested at once. Python stops at about 1000 by default, so very deep inputs need an explicit stack.
- safe integer
- In JavaScript, an integer up to 2^53 − 1 that a
numberrepresents exactly. Beyond it, useBigInt. - self-loop
- An edge from a node to itself. It is a cycle of length 1 and breaks some cycle checks.
- surrogate pair
- Two UTF-16 units that together encode one code point, such as most emoji. JavaScript
lengthcounts both. - disconnected graph
- A graph with more than one component. A single search from one node will miss the others.