Intermediate Level

Implement the productArrayExceptSelf method that returns an array where each value is the product of all other values.

The input contains an integer array nums and its length size. Your task is to return a new array where each index contains the product of all elements except the value at that same index.

For example, for [1,2,3,4], the result is [24,12,8,6] because each position multiplies all other values except itself.

Example 1

Input
nums (int[]) = [1,2,3,4]
size (int) = 4
Returns (int[]) [24,12,8,6]

Example 2

Input
nums (int[]) = [-1,1,0,-3,3]
size (int) = 5
Returns (int[]) [0,0,9,0,0]

Example 3

Input
nums (int[]) = [2,3]
size (int) = 2
Returns (int[]) [3,2]

Use prefix and suffix products so that each answer can be calculated without dividing.

First pass from left to right and store the product of all elements before each index. Then pass from right to left and multiply each position by the product of all elements after that index.

This also handles arrays containing zero because the method does not rely on division.

Pseudocode:

function productArrayExceptSelf(nums, size):
    answer = array of size values filled with 1
    prefix = 1
    for i from 0 to size - 1:
        answer[i] = prefix
        prefix = prefix * nums[i]
    suffix = 1
    for i from size - 1 down to 0:
        answer[i] = answer[i] * suffix
        suffix = suffix * nums[i]
    return answer
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.