What to look for
An off-by-one error happens when a loop, index, or count is shifted by 1. This often means something is included that should be excluded, or one item is missed.
A reliable method
- Read the goal first. Decide exactly which items should be counted or processed.
- Check the starting point. If indexing begins at 0, make sure the first element is handled correctly. If counting starts at 1, verify that the loop matches that choice.
- Check the stopping condition. Compare the last valid index or final count with the loop condition. A common mistake is using
< when <= is needed, or the reverse.
- Trace a tiny example. Test with 1, 2, or 3 items. Write down each step and see whether any item is skipped or repeated.
How to confirm the fix
- If an item is missing, the loop likely ends too early.
- If an extra item appears, the loop likely runs one step too far.
- After correcting the boundary, simplify the final answer by removing any unnecessary steps or repeated terms.
Quick check
For any counting problem, ask: “Does this process include exactly the intended items, no more and no less?” If yes, the off-by-one error is fixed.