Walking two lists at once with a carry

Linked Lists

Walking two lists at once with a carry

Arithmetic on lists, and the loop condition that handles both lists ending at different times.

Key idea

The shape

Walking two lists in parallel and combining them position by position is a common shape, and the interesting part is when to stop. There are three reasons to keep looping: the first list has more, the second has more, or there is something left over from the previous step.

Writing the condition as all three joined by or handles unequal lengths and a trailing carry without any special cases after the loop.

Why it works

The carry belongs in the loop condition

The second example is the reason. Adding 99 and 1 gives 100, which needs three digits from two-digit input. Both lists are exhausted and there is still a 1 to place.

Handling that after the loop with a trailing if carry also works and is one more thing to remember. Putting carry in the condition means the loop simply runs once more, and the same code writes the digit.

Tip

`divmod` gives both halves at once

divmod(total, 10) returns the quotient and remainder as a pair, which is exactly the new carry and the digit to store. It is clearer than computing total // 10 and total % 10 separately and cannot get the two swapped.

The order matters: quotient first, remainder second. Assigning them the wrong way round produces digits above nine and a carry that is always a digit, which is a distinctive enough symptom to recognize.

Edge cases

Which end is the least significant?

The code above assumes the least significant digit comes first, which is what makes the arithmetic natural: you add from the small end, exactly as by hand.

If the problem stores the most significant digit first, you either reverse both lists, add, and reverse the result, or use stacks to walk them backward. Check which order the problem states before writing anything, because the whole approach depends on it.

Predict the output: dropping the carry from the condition

This version stops as soon as both lists are exhausted, ignoring a leftover carry. Type what it prints.

Add Two Numbers

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

Loading the workspace…
← Previous