Algo-Sim › Arrays & Hashing

Product of Array Except Self

Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input

answer[i] is the product of every element except nums[i], computed without division from prefix and suffix products.

Problem

Given an integer array nums, build an array answer where answer[i] is the product of every element of nums except nums[i]. Do it in O(n) time without using division.

Constraints

Edge cases to test

Follow-up questions

Can you do it in O(1) extra space?
Write the prefix products into the output array, then sweep from the right with one running suffix product: O(n) time, O(1) extra.
Why not divide the total product by nums[i]?
Division fails on zeros (and the task forbids it). Counting zeros and dividing works but overflows sooner than prefix and suffix products.

Solution

Java

public int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] answer = new int[n];
    answer[0] = 1;
    for (int i = 1; i < n; i++) {
        answer[i] = answer[i - 1] * nums[i - 1];
    }
    int suffix = 1;
    for (int i = n - 1; i >= 0; i--) {
        answer[i] *= suffix;
        suffix *= nums[i];
    }
    return answer;
}

Python

def product_except_self(nums):
    n = len(nums)
    answer = [1] * n
    for i in range(1, n):
        answer[i] = answer[i - 1] * nums[i - 1]
    suffix = 1
    for i in range(n - 1, -1, -1):
        answer[i] *= suffix
        suffix *= nums[i]
    return answer

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> productExceptSelf(vector<int> &nums) {
        int n = int(nums.size());
        vector<int> answer = vector<int>(n);
        answer[0] = 1;
        for (int i = 1; i < n; i++) {
            answer[i] = answer[i - 1] * nums[i - 1];
        }
        int suffix = 1;
        for (int i = n - 1; i >= 0; i--) {
            answer[i] *= suffix;
            suffix *= nums[i];
        }
        return answer;
    }
};

More Arrays & Hashing problems