Product of Array Except Self Problem & Solution

See the product of array except self problem on LeetCode.

C++ Solution

#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")
#pragma GCC target("avx,avx2,fma")

static const int _=[](){ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();

class Solution {
public:
  vector<int> productExceptSelf(vector<int>& nums) {
    vector<int> prev(nums.size(), 1),
                next(nums.size(), 1),
                results(nums.size());

    for (int i = 1; i < nums.size(); ++i) {
      prev[i] = prev[i - 1] * nums[i - 1];
    }

    for (int i = nums.size() - 2; i >= 0; --i) {
      next[i] = next[i + 1] * nums[i + 1];
    }

    for (int i = 0; i < nums.size(); ++i) {
      results[i] = prev[i] * next[i];
    }

    return results;
  }
};

Start Here

Many Paths. Follow Yours.