Scrivio Interview library
Arrays and hashingArrays and stringsReported 16 times · 15 min read · updated 15 November 2026

Build an array where each position holds the product of all other elements, without using division.

1What it means to multiply everything except one position

Imagine four students sitting in a row, each holding a card with a number on it, 2, 3, 4 and 5. The teacher asks each student to write down the product of everybody else's numbers, the result of multiplying them together, but not their own. The student holding 2 needs 3 times 4 times 5, which is 60. The student holding 4 needs 2 times 3 times 5, which is 30. Each student can see the whole row, so each could simply multiply the other three. But there is a smarter way to share the work, and it is the whole of this problem.

Here is the question in plain words. We are given an array of numbers, nums, and must build a second array of the same length, result, where result[i] is the product of every number in nums except the one at position i. Position, or index, starts at 0 in Java. There is one rule that makes the question interesting. We may not use division.

Why forbid division? The tempting shortcut is to multiply everything once, 2 times 3 times 4 times 5 = 120, and then divide by each number, giving 60, 40, 30 and 24. It works here, but if any number is 0 the total is 0, and dividing by 0 is not allowed, so the shortcut breaks exactly when the array holds a zero. The interviewer wants a method that never needs it. That sounds hard, but as we will see, it needs nothing more than multiplying in a careful order, and the answer is simpler than it first looks.

Our example is nums = 2, 3, 4, 5, and the answer is 60, 40, 30, 24. Work out one of them yourself before reading on. For index 1, leave out the 3 and multiply 2 times 4 times 5, which is 40. The picture shows the input above and the answer below.

PictureThe example and the answer we must build

Top row is nums. Bottom row is result, where each cell is the product of the other three numbers.

  1. 234560403024

    1The top row is nums = 2, 3, 4, 5. The bottom row is the answer 60, 40, 30, 24. For example, 40 is 2 times 4 times 5, leaving out the 3.

What to assume

Can the array hold zeros or negative numbers?
We assume yes to both.
Can the products be too large for an int?
We assume the interviewer promises they fit.
Does the result array count as extra space?
Usually not, because we must return it anyway, and the interviewer will often ask for constant extra space beyond it.

A careful candidate asks a few questions first. Can the array hold zeros or negative numbers? We assume yes to both, and the method will handle them without special cases. Can the products be too large for an int? We assume the interviewer promises they fit, and we mention long otherwise. Does the result array count as extra space? Usually not, because we must return it anyway, and the interviewer will often ask for constant extra space beyond it.

2How to recognise a left and right running product problem

A beginner reading this question for the first time usually reaches for two loops, one choosing the position and one multiplying all the others. That is correct, and we will try it next. But two nested loops over the same array are a signal worth noticing, because they often mean the same work is being done again and again.

So let us read the question slowly and take the clues one at a time. The first clue is the phrase all other elements. Everything except position i splits naturally into two groups, the numbers to the left of i and the numbers to the right of i. For index 2 in our example, the left group is 2 and 3, and the right group is 5. Leaving out one element is the same as joining what lies before it with what lies after it.

The second clue is the word product, which is built up one number at a time. If we already know the product of the first two numbers, 6, then the product of the first three is just 6 times 4. Nothing has to be multiplied again. A total that grows one element at a time like this is called a running total, and when it is built from the left it is called a prefix, because it covers the front of the array. Built from the right it is a suffix.

The third clue is the ban on division, which rules out the shortcut and tells us the interviewer expects this left and right idea. Together the clues point to the arrays and hashing pattern, the family of problems where one or two careful passes over an array, keeping a little remembered information, replace nested loops. Hashing is not needed here; the remembered information is a running product rather than a map. The rule to carry to new problems is this. When each answer depends on everything before and everything after a position, compute a running total from the left and another from the right, and combine them.

Some patterns look similar but do not fit. A sliding window, a frame of fixed or changing size moved along the array, deals with a stretch of neighbours, but here each answer needs the whole array except one place. A hash map would remember values we have seen, but we never need to look a value up, only to multiply in order.

3The honest brute force, multiplying all the others for each position

The honest first attempt is a brute force, which simply does what the question says, one position at a time. For each index i, we start a product at 1, multiply in every number whose index is not i, and store the result. It is correct and easy to check, which is exactly what a first attempt should be.

Step throughThe brute force multiplies the same numbers again in every row

Each row is the work for one position, with the left-out number dimmed. The second frame shows each row split into its left part and its right part.

  1. 2345234523452345

    1Row i is the work for result[i]. The dimmed cell is left out, and the other three are multiplied, twelve multiplications in all.

  2. 2345234523452345

    2Split each row at the dimmed cell. Compared cells are the left part, marked cells the right part. Rows 2 and 3 both redo 2 times 3, and rows 0 and 1 both redo 4 times 5.

Java
// Brute force: for each position, multiply all the other elements again.
static int[] productExceptSelf(int[] nums) {
int[] result = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int product = 1;
for (int j = 0; j < nums.length; j++) {
if (j != i) product *= nums[j]; // every element except position i
}
result[i] = product;
}
return result;
}

Let us run it by hand. For index 0 the inner loop multiplies 3, 4 and 5 to get 60. For index 1 it multiplies 2, 4 and 5 to get 40. For index 2 it multiplies 2, 3 and 5 to get 30, and for index 3 it multiplies 2, 3 and 4 to get 24. The answer is right. The inner loop ran 4 times for each of 4 positions, 16 steps with 12 multiplications. For an array of n numbers it runs n times n steps, so the time is O(n squared), which means doubling the array makes the work four times larger. For a hundred thousand numbers that is ten billion steps. The extra space is a single variable, O(1).

So where is the waste? Look at the picture. Each row is one position's work, with the left-out number dimmed. In the second frame the numbers before the dimmed cell are marked in one colour and those after it in another. Row 0 multiplies 4 and 5, and row 1 multiplies 4 and 5 again. Row 2 multiplies 2 and 3, and row 3 multiplies 2 and 3 again. In a longer array the repeats pile up, because every row recomputes long stretches that the row above already multiplied.

4Getting to two walks, one observation at a time

The second frame of that picture holds the whole idea. Every row is a left part times a right part. The left parts, read down the rows, are nothing, then 2, then 2 times 3, then 2 times 3 times 4. Each one is the previous one times one more number. The right parts, read up from the bottom, grow the same way from the other end. So instead of recomputing them, we can build all the left products in one walk from left to right, and all the right products in one walk from right to left.

Go back to the students in the row. A note starts at the left end with the number 1 written on it. The first student copies down what the note says, 1, then multiplies the note by their own card, 2, and passes it on. The second student copies 2, multiplies the note by 3 and passes on 6. The third copies 6 and passes on 24, and the fourth copies 24. Each student now holds the product of everyone to their left. Then a second note starts at the right end with 1 and travels back the same way, and each student multiplies what they wrote by what the second note says when it arrives.

Here a beginner usually asks a fair question. Why does each student copy the note before multiplying in their own number, and not after? Let us try it the other way and see what we lose. If the first student multiplied first, the note would say 2, they would copy 2, and their own number would be inside their answer, which is exactly what the question forbids. Copying first means the note holds only the numbers strictly before this student. The order of those two actions is the heart of the method.

For the left walk we need a single running variable, left, starting at 1, and for each i we do result[i] = left and then left = left times nums[i]. After this walk result holds 1, 2, 6, 24, the products of everything to the left of each position. Why start at 1? Because the first position has nothing to its left, and 1 is the number that changes nothing when you multiply by it. The product of no numbers at all is taken to be 1.

For the right walk we use a second variable, right, also starting at 1, and go from the last index down to 0, doing result[i] = result[i] times right and then right = right times nums[i]. Each position already holds its left product, and now we multiply in its right product. Why is this correct? When we reach position i on the way back, right holds exactly the product of the numbers after i, for the same reason left held the numbers before it, so result[i] becomes left part times right part, which is everything except nums[i].

5Watching both walks fill the result array

The picture plays both walks on 2, 3, 4, 5, exactly as the Java code runs them. The cells show the result array, the pointer i shows the position being worked on, and the panel shows nums and the running product. In the first half, watch each cell receive the left product before left grows. In the second half, watch each cell be multiplied by right before right grows.

Step throughTwo walks build 60, 40, 30, 24 without division

The cells are the result array. The first walk writes the product of everything to the left; the second multiplies in the product of everything to the right.

  1. 00010203i
    nums
    2, 3, 4, 5
    left
    1

    1Java fills a new int array with zeros. The running product left starts at 1, because nothing lies to the left of index 0.

  2. 10010203i
    nums
    2, 3, 4, 5
    left
    2

    2At i = 0 we write left, which is 1, into result[0], then multiply left by nums[0] = 2, so left becomes 2.

  3. 10210203i
    nums
    2, 3, 4, 5
    left
    6

    3At i = 1 we write left = 2, the product of everything before index 1, then multiply left by 3, so left becomes 6.

  4. 10216203i
    nums
    2, 3, 4, 5
    left
    24

    4At i = 2 we write left = 6, which is 2 times 3, then multiply left by 4, so left becomes 24.

  5. 102162243i
    nums
    2, 3, 4, 5
    left
    120

    5At i = 3 we write left = 24, then left becomes 120. Every cell now holds the product of the numbers to its left.

  6. 102162243i
    nums
    2, 3, 4, 5
    right
    5

    6The second walk starts at the right with right = 1. At i = 3, result[3] = 24 times 1 = 24, then right becomes 5.

  7. 1021302243i
    nums
    2, 3, 4, 5
    right
    20

    7At i = 2, result[2] = 6 times right = 5, giving 30, then right becomes 5 times 4 = 20.

  8. 10401302243i
    nums
    2, 3, 4, 5
    right
    60

    8At i = 1, result[1] = 2 times right = 20, giving 40, then right becomes 20 times 3 = 60.

  9. 600401302243i
    nums
    2, 3, 4, 5
    right
    120

    9At i = 0, result[0] = 1 times right = 60, giving 60, then right becomes 120, though nobody needs it now.

  10. 600401302243
    nums
    2, 3, 4, 5
    result
    60, 40, 30, 24

    10Both walks are done. The result is 60, 40, 30, 24, built from the two sides of each position without a single division.

Let us read the important frames back. After the fifth frame the result array holds 1, 2, 6, 24, the left products, exactly the numbers the students copied from the first note. The sixth frame starts the second note at the right end. Look at the seventh frame, at index 2. The cell held 6, which is 2 times 3, the part on its left, and right held 5, the part on its right. Their product, 30, is everything except the 4.

Notice that left ends at 120 in the fifth frame and right ends at 120 in the ninth, the product of the whole array. We never use that number, and that is why division is never needed. Each answer is assembled from its two sides instead of taken away from the whole.

6The complete Java program

Here is the complete program. productExceptSelf does the two walks, and main runs the example, an array with one zero, an array with two zeros and a short array with a negative number.

Java
import java.util.Arrays;
public class ProductExceptSelf {
// result[i] = product of every element except nums[i], without division.
static int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] result = new int[n];
int left = 1; // product of everything before i
for (int i = 0; i < n; i++) {
result[i] = left;
left *= nums[i];
}
int right = 1; // product of everything after i
for (int i = n - 1; i >= 0; i--) {
result[i] *= right; // before-product times after-product
right *= nums[i];
}
return result;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(productExceptSelf(new int[] {2, 3, 4, 5}))); // [60, 40, 30, 24]
System.out.println(Arrays.toString(productExceptSelf(new int[] {1, 2, 0, 4}))); // [0, 0, 8, 0]
System.out.println(Arrays.toString(productExceptSelf(new int[] {0, 2, 0}))); // [0, 0, 0]
System.out.println(Arrays.toString(productExceptSelf(new int[] {-1, 3}))); // [3, -1]
}
}

Let us read productExceptSelf in the order it runs. It creates result with the same length as nums. Then left starts at 1, and the first loop goes from index 0 upwards. Inside, result[i] = left comes first, because it must record the product of the numbers strictly before i, and only then does left *= nums[i] add the current number for the positions still to come. Swapping those two lines is the most common mistake here, and it quietly puts each number into its own answer.

The second loop starts right at 1 and goes from the last index down to 0. result[i] *= right multiplies the left product already stored there by the product of everything after i. Then right *= nums[i] grows the running product for the positions to the left. Again the order matters for the same reason. When the loop ends, every cell has been multiplied by both of its sides, and we return result.

Now the zeros, which the division shortcut could not handle. For 1, 2, 0, 4 the left walk writes 1, 1, 2, 0, and left becomes 0 after it passes the zero. The right walk multiplies index 3 by 1, giving 0, index 2 by 4, giving 8, and then right has passed the zero, so indexes 1 and 0 become 0. The answer is 0, 0, 8, 0, which is right, because every answer except the zero's own includes the zero. With two zeros, as in 0, 2, 0, every position has a zero on at least one side, so everything is 0.

7How much it costs, and the cases at the edges

Let us count on the example first. The left walk did one multiplication at each of 4 positions and the right walk did two, 12 in all, the same 12 the brute force needed. For four numbers that looks like a tie, but the two grow differently. For n numbers the walks do about 3n multiplications, so the time is O(n), while the brute force does about n squared. For a hundred thousand numbers that is three hundred thousand against ten billion.

The extra space is two variables, left and right, whatever the size of the array, so O(1) beyond the result array we must return anyway. A common first version keeps two whole arrays, one of left products and one of right products, and multiplies them together at the end. It is just as fast and a good stepping stone, but it uses O(n) extra space, which our version avoids by storing the left products directly in result.

Comparing the ways to build the products
ApproachTimeExtra spaceHandles zeros?
Multiply all others for each positionO(n squared)O(1)yes
Total product, then divide (not allowed)O(n)O(1)no, a zero breaks it
Separate left and right arraysO(n)O(n)yes
Left products in result, then a right walkO(n)O(1) beyond the outputyes

Now the edge cases. Zeros and negative numbers need no special code, as main shows. With two numbers, -1 and 3, each answer is simply the other number, and the code prints 3, -1. With a single number, the product of no numbers is 1, so the code returns an array holding 1. If the products can grow beyond about two billion, the int variables overflow silently, so we would change left, right and result to long, or agree with the interviewer that the answer fits.

8Follow-up questions

Why is the result array not counted as extra space?

Because any solution must create and return an array of n answers, so that memory is the output, not something the method chose to spend. Extra space means memory used beyond what we hand back. Our method uses two int variables on top of the result, which is O(1). The two-array version keeps n left products and n right products besides the result, which is O(n). If the interviewer counts the output too, both are O(n), and it is worth saying so plainly.

How would you do this with division if it were allowed?

Count the zeros first. If there are none, multiply everything once and divide the total by each number. If there is exactly one zero, every position gets 0 except the zero's own position, which gets the product of all the other numbers. If there are two or more zeros, every answer is 0. It is O(n) as well, but it needs those three cases, which is one reason the interviewer prefers the two-walk method.

Where else does the left and right running total idea appear?

It appears whenever each answer depends on both sides of a position. Trapping rain water uses the tallest bar to the left and to the right of each position. Finding an index where the sum on the left equals the sum on the right uses running sums from both ends. The shape is always the same, a walk from the left storing one fact per position, a walk from the right combining the other fact.

9Conclusion

We built each product of all other elements by splitting the job into two sides. A walk from the left writes into each position the product of everything before it, copying the running product before multiplying in the current number, and a walk from the right multiplies in the product of everything after it in the same careful order. It costs O(n) time and O(1) extra space, handles zeros with no special cases, and never divides. The clue to remember is all other elements: everything except one position is what lies before it joined with what lies after it.

What to say in the interviewAbout 80 seconds aloud

Open with

Let me confirm the rules. I return an array where each position holds the product of all the other numbers, I cannot use division, zeros and negatives are allowed, and I can assume the products fit in an int.

Then, if they want more

The brute force multiplies all the other numbers for each position, which is O(n squared), and most of that work is repeated, because neighbouring positions share almost all of their factors. The product of everything except position i is the product of everything to its left times everything to its right. So I make two passes.

In the first, I keep a running product called left, starting at 1. At each index I store left into the result, then multiply left by the current number, so each cell gets the product strictly before it.

In the second pass I go from the right with a running product called right, also starting at 1, multiply the result cell by right, then multiply right by the current number. That is O(n) time, and O(1) extra space beyond the output array. Zeros need no special handling, which is exactly where the division approach fails.

About this answer

Last updated
15 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 16 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Build an array where each position holds the product of all other elements, without...": https://scrivio-interview-library.netlify.app/data-structures/solutions/build-an-array-where-each-position-holds-the-product-of-all-othe-5a8f3c/