Problem in simple words
Given two non-negative integers represented as strings, return their product as a string.
Core idea
The product of digits at i and j contributes to positions i + j and i + j + 1.
How the algorithm thinks
- 1
Prepare a zero-filled output array
VISITThe output needs to be large enough to hold any possible product before any digit pair is multiplied.
Watch: The initial zero-filled output array.
- 2
Multiply the current digit pair
UPDATEEach digit from one number multiplied by each digit from the other contributes one piece of the final product.
Watch: The current digit pair and their product.
- 3
Write the digit and carry into fixed offsets
ADDThe product's ones digit lands at one offset, while its carry lands at the neighboring offset, mirroring hand multiplication.
Watch: The output array positions being updated.
- 4
Return the joined product
RETURNOnce every digit pair has contributed and carries have settled, the output array reads out as the final product.
Watch: The final product string.
Step-by-step logic
- -Create an output array of zeros sized to the sum of both input lengths -- large enough for any possible product.
- -For every digit i in the first number and every digit j in the second number, compute their product plus whatever is already at output offset i+j+1.
- -Write that value's ones digit at offset i+j+1, and add its carry into offset i+j.
- -Once every digit pair has contributed, join the output array into a string and strip any leading zero.
Complexity
Time O(nm)·Space O(n+m)
every pair of digits contributes once to the output array.
Implementation
This is the JavaScript implementation that generates the simulator timeline.
function multiply(input) {
for every digit pair, add product into output offsets;
normalize carries and join digits;
}Common mistakes
Pause before the next step and name the state change you expect.
Watch the active pointers, discarded range, and output state and match it to the highlighted code line.
Say the rule that never breaks (the invariant) out loud: what remains true before and after this step?
- -Step 1: a[2]='3' × b[2]='6' = 18. Write 8 at offset 5, carry 1 into offset 4.
- -Step 2: a[2]='3' × b[1]='5' = 15, plus the 1 already at offset 4 = 16. Write 6 at offset 4, carry 1 into offset 3.
- -Step 3: continuing every digit pair (a[2]×b[0], a[1]×b[2], a[1]×b[1], a[1]×b[0], a[0]×b[2], a[0]×b[1], a[0]×b[0]) accumulates and carries through the remaining offsets.
- -Step 4: after every pair has contributed, the output array reads [0,5,6,0,8,8], which joins (after trimming the leading zero) to "56088".
- - Decide what each pointer represents.
- - Move the pointer that can safely eliminate work.
- - Keep the invariant true after every move.
Build the reasoning before opening the simulator
Turn the mental model into a short decision checklist, then compare it with the execution timeline.