Back to Dashboard

Product of Array Except Self

Medium

Problem 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].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Examples

Example 1:

  • Input: nums = [1,2,3,4]
  • Output: [24,12,8,6]

Approach 1: Brute Force

class Solution {
    public int[] productExceptSelf(int[] nums) {
        var n = nums.length;
        var ans = new int[n];
        Arrays.fill(ans, 1);
        var curr = 1;
        for (int i = 0; i < n; i ++) {
            ans[i] *= curr;
            curr *= nums[i];
        }
        curr = 1;
        for (int i = n - 1; i >= 0; i --) {
            ans[i] *= curr;
            curr *= nums[i];
        }
        return ans;
    }
}

Status

Solved

Complexity

Time
O(n)
Space
O(1)

Tags

ArrayBlind-75
View Problem Source