A girl and a robot thinking together

Think together · First, a short story

The robot calculates a total incorrectly. Instead of changing code at random, the girl finds the smallest input that still fails.

Lay out the process

Follow the numbered steps, then explain them in your own words.
  1. Keep the failing input2, 3
  2. Write the expected resultIt should be 5
  3. Observe step by stepWhen does a value go wrong?
  4. Fix and retestConfirm the cause

Debugging starts with an error you can reproduce.

Shrink the input, record the program state, and find the first point where it differs from what you expected. After a fix, run the same failing case again to confirm the problem is gone.

01What is the first step in debugging?

First, make the error reproducible.

Record a specific input, the incorrect output you got, and the correct answer.

02Step 2: make the failing input smaller

If 1,000 values cause a failure, try reducing them to 10, then 5, or even 2, while keeping the failure.

03Step 3: trace the program state

You can draw a table or print temporary values:

StepisumCurrent element
1055
21127

04Step 4: find where it first goes wrong

Do not focus only on the final incorrect answer.

Everything is correct so far→One step first goes wrong→Inspect this part closely

05Step 5: form a hypothesis

For example:

  • Does the loop run one step too far?
  • Is a variable's initial value wrong?
  • Is there an integer overflow?
  • Is visited marked too late?

Then verify your idea with output or a debugger instead of changing code blindly.

06Why test again after a change?

A fix for one input may break another case.

At a minimum, retest:

  • The original failing case
  • The official samples
  • Boundary cases
  • A few ordinary test cases

07When should you use a debugger?

When the program state is complex, use breakpoints, step execution, variable inspection, and the call stack.

What have you learned?

  • Make the error reproducible before debugging.
  • Shrinking the failing input makes analysis easier.
  • Finding the first wrong step is more useful than looking only at the final answer.
  • Form a hypothesis and verify it with evidence.
  • Always run regression tests after a fix.

Next: How can you estimate whether your program will time out?

Your turn to try

A program fails occasionally. What should you do first after finding an input that triggers the failure?

Ready? Open the explanation

Save the input and actual output, then write down the expected result. This lets you reproduce the issue after each change.