Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 63 ยท Contest Toolkit

Edge Cases and Common Pitfalls

A checklist of the mistakes that cost contestants points: n = 1, empty input, overflow, negative numbers, division and modulo rules, duplicates and float comparison.

Most wrong answers in contests do not come from a wrong algorithm. They come from a correct algorithm meeting an input the author did not imagine: a single element, an empty line, all numbers equal, a negative value, a sum that does not fit in 32 bits. Judges love these tests because they are cheap to write and catch many solutions.

This lesson is a practical checklist. For each pitfall you will see how it shows up, what Python does about it and what changes if you later write the same solution in C++ or Java. Pair it with stress testing: a generator that produces small sizes and small value ranges hits nearly every item below by accident.

The checklist before you submit

Run through these questions on every problem. They take a minute and save many penalties.

flowchart TD
  A["Solution passes samples"] --> B{"n = 1 or n = 2<br/>handled?"}
  B -- "no" --> X["Fix and retest"]
  B -- "yes" --> C{"All equal values,<br/>duplicates, zeros?"}
  C -- "no" --> X
  C -- "yes" --> D{"Negative numbers<br/>and max values?"}
  D -- "no" --> X
  D -- "yes" --> E{"Output format and<br/>empty answer?"}
  E -- "no" --> X
  E -- "yes" --> F["Submit"]

A short pre-submit checklist: small sizes, repeated values, extreme values, then output format.

Smallest inputs: n = 1, n = 0 and empty lines

Code that looks at a[1], compares neighbours, or divides by n - 1 often breaks when the input is tiny. Typical cases:

  • n = 1. There are no pairs, no neighbours and no gaps. "Maximum difference between adjacent elements" has no answer, so the statement must say what to print; read it.
  • n = 0 or an empty string. max([]) raises ValueError and min([]) too. Pass default= or check the length first.
  • Empty lines. A test may contain a blank line where a list of zero numbers belongs. input().split() correctly returns [], but int(input()) on an empty line crashes.
  • k larger than n. A window of size k over fewer than k elements has no valid position.
Python Guarding against tiny inputs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Overflow: C++ and Java versus Python

In C++ and Java an int is 32 bits and holds values only up to 2,147,483,647. A long long holds about 9.2 * 10^18. Adding or multiplying past the limit does not raise an error; it silently wraps around to a wrong (often negative) number. Typical triggers:

  • A sum of 2 * 10^5 values each up to 10^9 reaches 2 * 10^14. That needs 64 bits.
  • A product of two values near 10^9 reaches 10^18, which is right at the edge of 64 bits. Multiplying three such values overflows even 64 bits.
  • a * b % m with a, b close to m = 10^9 + 7 is fine in 64 bits, but a * b * c % m must take the modulo after each multiplication.

Python integers have arbitrary size, so none of this happens and you can write the natural formula. That is a real advantage, but two traps remain. First, if your solution is later ported to a typed language, remember the limits. Second, huge numbers are slow: multiplying numbers with thousands of digits costs far more than a machine multiply, so avoid letting values grow without a modulo when the statement asks for the answer "modulo m". The modular arithmetic lesson covers this in depth.

The next example mimics a 32-bit signed integer in Python so you can see what a typed language would print:

Python What 32-bit and 64-bit integers would do

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 32-bit sum of the first 100,000 integers wraps to a number that is not even close to 5,000,050,000. A contest solution in C++ that used int here would print garbage on large tests but pass small ones, which is exactly the pattern of "passes samples, fails test 12".

Negative numbers, division and modulo

Python and C++/Java disagree about how negative numbers divide.

Expression Python C++ / Java
-7 // 2 or -7 / 2 -4 (rounds down) -3 (rounds toward zero)
-7 % 3 2 (result has the sign of the divisor) -1 (sign of the dividend)

Python's rule is usually the friendlier one: x % m always lands in 0..m-1 for a positive m, which is exactly what modular problems want. In a typed language you must write ((x % m) + m) % m to get the same result.

The opposite trap is when a problem expects truncation toward zero (for example, "integer division as defined in C") and you use //. Use int(a / b) for small values, or compute the sign yourself for large ones, because a / b in Python is a float with only 53 bits of precision.

Python Floor versus truncating division and modulo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines matter in binary search. With negative bounds, (lo + hi) // 2 rounds down and (lo + hi) / 2 in C++ rounds toward zero, so a loop that relies on mid < hi can behave differently across languages. The binary search lesson returns to this.

Duplicates, ties and sorted assumptions

Algorithms often silently assume distinct values. Ask what happens when:

  • two items have the same key (is the sort stable? Does the tie-break matter?);
  • all elements are equal (a "second largest distinct value" may not exist);
  • the answer set is empty (print -1? print nothing? print 0?);
  • a number repeats inside a set or dict, shrinking the count you expected.

Counting distinct values with a set and then using len(a) later is a typical slip. When you need the second largest distinct value, work on sorted(set(a)) and check the length.

Floating point

Floats cannot represent most decimals exactly, so never compare them with == for results of arithmetic, and avoid them entirely when the data is integral.

Python Why == fails on floats and what to use instead

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rules of thumb: keep everything in integers if you can (cross-multiplying fractions, using math.isqrt, scaling money to cents); when floats are unavoidable, compare with a tolerance such as abs(x - y) < 1e-9; and print with a fixed number of decimals (f"{x:.10f}") because the judge's checker usually accepts a small error but cannot parse something like 1e-05 in every setup.

Output pitfalls

  • Trailing spaces and blank lines. Most judges ignore trailing whitespace, but a few strict ones do not. Join with " ".join(map(str, ans)).
  • Yes/No case. If the statement says YES/NO, then Yes may be rejected.
  • Printing a list. print(ans) prints brackets and commas. Unpack it with print(*ans).
  • Large outputs. Thousands of separate print calls are slow; build a list of strings and print once with "\n".join(out).
  • Multiple tests. Reset per-test state. A global list that is not cleared between test cases carries data from one case into the next and fails only on multi-test inputs.

Building an edge-case habit

When you finish a solution, write down the most hostile input you can think of before running anything: the smallest, the largest, all equal, strictly sorted, reverse sorted, alternating. Then run those by hand or through your template. Keep a short personal list of mistakes you have made; the same ones repeat for years.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In C++, what is -7 / 2 (integer division), and what does Python's -7 // 2 give?

    C++ truncates toward zero (-3). Python floors toward negative infinity (-4).
  2. 2. Which tiny input most often breaks code that compares neighbouring elements?

    With one element there are no neighbour pairs, so loops that start at index 1 or take min/max over pairs may fail or need a special answer.
  3. 3. Why does a 32-bit int solution to a sum of 100,000 values up to 10^9 give a wrong answer?

    A 32-bit signed integer holds at most about 2.1 * 10^9. Larger sums wrap around without any error message.
  4. 4. What is the safest way to test whether two fractions a/b and c/d are equal using only integers?

    Cross-multiplying stays in exact integer arithmetic, while division produces floats that can be rounded differently.
  5. 5. Why use math.isqrt(n) instead of int(math.sqrt(n)) for large n?

    math.sqrt converts to a float, which loses precision above about 2^53. math.isqrt works on integers exactly.

Summary

  • Always test n = 1, n = 2, empty data, all-equal values, duplicates, zeros and negative numbers.
  • Python integers do not overflow, but C++/Java ones do: use 64-bit types and take the modulo after each multiplication.
  • Python floors on // and keeps % non-negative for a positive modulus; C++ and Java truncate toward zero.
  • Prefer exact integer arithmetic over floats; use math.isclose, a tolerance, or math.isqrt when needed.
  • Check output format, case, separators and per-test state resets.
  • Keep a personal list of the mistakes you repeat.

Next: Implementation Problems