Skip to content

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.

20 min read0/8 questions

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 lineEdge cases it promises
0 <= nums.length <= 10^5[] is a real test. Also the largest size, for speed.
1 <= nums.lengthNo empty input, but one element will be tested.
-10^9 <= nums[i] <= 10^9Negatives, zero, and sums near 10^14 (overflow in 32-bit languages).
1 <= k <= nums.lengthk = 1 and k = n, the whole array.
no "distinct" promiseDuplicates, 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.lengthA graph with no edges: every node is its own component.
edges may contain cyclesA 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 pairs0/5 matched

Match the constraint line to the edge case it most strongly suggests.

Choose an item, then its match on the other side.

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.

  1. Empty: [], "", no nodes, no intervals.
  2. One element: a single number, one character, a one-node tree.
  3. Two elements: the smallest case where pairs, swaps, and neighbours exist.
  4. All the same: [5, 5, 5, 5]. Breaks "strictly greater" logic and duplicate skipping.
  5. Duplicates: equal values at different positions.
  6. Negatives and zero: breaks sliding windows on sums, product logic, "largest is last after sorting".
  7. Overflow: the largest values added or multiplied together.
  8. Already sorted / reverse sorted: the worst case for naive quicksort, the best or worst case for greedy scans.
  9. No valid answer: return -1, 0, [], or false as the prompt says.
  10. Graphs: cycles and disconnected parts: a DFS without a visited set loops forever on a cycle, and a single BFS from node 0 misses a second component.
  11. The maximum size: for speed, and for recursion depth.
Quick check
A recursive DFS passes all small tests but crashes on a linked list of 10^5 nodes in Python. Why?
Need a nudge? A hint rules out a wrong answer.

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.

Largest product of two numbers
-10
0
-9
1
1
2
2
3

Sorted input with two negatives. The constraint said -10^4 <= nums[i] <= 10^4, so negatives were promised.

1/4
Predict the outputPython

What does the tempting version print?

nums = sorted([-10, -9, 1, 2])
print(nums[-1] * nums[-2])
Need a nudge? Hints walk you through it.

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.

Quick check
Two Sum: a solution builds the whole map 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?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the edge-case routine in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick checkPick all that apply
Constraints: 1 <= prices.length <= 10^5, 0 <= prices[i] <= 10^4. Which edge cases are worth testing? (Pick all that apply.)

None picked yet

Need a nudge? A hint rules out a wrong answer.

Overflow and precision

The value ranges in the constraints tell you whether arithmetic is safe. Each language fails differently.

  • Java, C++, Go: int is 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-bit long. The classic hidden bug is mid = (lo + hi) / 2 overflowing, which is why you see lo + (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 // 2 is -4).
  • JavaScript: every number is a 64-bit float, exact only up to Number.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. Use BigInt for the multiply, or split the multiplication.
  • Floats in any language: 0.1 + 0.2 is not exactly 0.3. Compare with a tolerance, or keep values as integers (cents, not dollars) when the problem allows.
JavaScript
// 1. Integers: exact only up to 2^53 - 1console.log(Number.MAX_SAFE_INTEGER);console.log(2 ** 53 === 2 ** 53 + 1); // true: precision is gone // 2. Modular products overflow precision before the % runsconst MOD = 1_000_000_007;const a = 999_999_999, b = 999_999_999;console.log((a * b) % MOD); // wrong: a * b was roundedconsole.log(Number((BigInt(a) * BigInt(b)) % BigInt(MOD))); // right // 3. Floatsconsole.log(0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < 1e-9); // 4. Strings: length counts UTF-16 units, not charactersconst s = "a\u{1F600}b";console.log(s.length, [...s].length);console.log(s.split("").reverse().join("") === [...s].reverse().join(""));
Output
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.

Predict the outputJavaScript

What does this print in JavaScript?

console.log(2 ** 53 === 2 ** 53 + 1);
Need a nudge? Hints walk you through it.

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 | null will be tested with null. That is the empty tree, not an error.
  • An array parameter typed number[] can be [], but on most platforms is never null unless the type says so. Do not litter the code with null checks the type rules out.
  • undefined in 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 becomes NaN. Treat any NaN in your output as an index-past-the-end bug.
  • Strings: "" is a valid string with length 0. Check s.length === 0 (or not s in 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 n but in no edge: they still count as components, so loop over range(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.

Quick check
Graph Valid Tree: 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?
Need a nudge? A hint rules out a wrong answer.

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.
Python
# A path graph 0 - 1 - 2 - ... - 99999: as deep as a graph getsn = 100_000adj = {i: [i + 1] for i in range(n - 1)}adj[n - 1] = [] def dfs_recursive(u, seen): seen.add(u) for v in adj[u]: if v not in seen: dfs_recursive(v, seen) try: dfs_recursive(0, set())except RecursionError as e: print("recursive:", type(e).__name__) def dfs_iterative(start): seen, stack = {start}, [start] while stack: u = stack.pop() for v in adj[u]: if v not in seen: seen.add(v) stack.append(v) return len(seen) print("iterative visited:", dfs_iterative(0))
Output
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. length counts 16-bit units. Most emoji and many rare symbols are two units (a surrogate pair), so "a\u{1F600}b".length is 4, not 3. s.split("") cuts pairs in half, so reversing that way produces broken characters. The spread [...s] and Array.from(s) iterate by code point instead.
  • Python strings are code points. len and 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.Segmenter in 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.

ChallengeEasy

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^5
  • 0 <= prices[i] <= 10^4
def max_profit(prices: list[int]) -> int: # Track the cheapest price so far as you walk forward. pass
Key terms
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 number represents exactly. Beyond it, use BigInt.
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 length counts both.
disconnected graph
A graph with more than one component. A single search from one node will miss the others.