Search⌘ K
AI Features

Product of All Array Elements Except Self

Explore how to compute an array where each element is the product of all other elements except itself. Understand the optimized technique involving left and right product arrays to achieve an O(n) time complexity. This lesson helps you solve a common coding interview problem efficiently while analyzing time and space trade-offs.

Statement

Given an integer array, nums, return an array, answer, such that answer[i] is equal to the product of all the elements of nums except nums[i].

Examples

Example 1

Sample input

nums = [1, 2, 3, 4]

Expected output

[24, 12, 8, 6]

Example 2

Sample input

nums = [-1, 1, 0, -3, 3]

Expected output

[0, 0, 9, 0, 0]

Try it yourself

#include <vector>
#include <iostream>
using namespace std;
vector<int> ProductExceptSelf(vector<int> nums) {
vector<int> answer;
// write your code here
return answer;
}

Solution

Naive approach:

The naive solution ...