DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

4 1

LeetCode 238. Product of Array Except Self

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];

        for (int i = 0, temp = 1; i < len; i++) {
            ans[i] = temp;
            temp *= nums[i];
        }
        for (int i = len - 1, temp = 1; i >= 0; i--) {
            ans[i] *= temp;
            temp *= nums[i];
        }

        return ans;
    }
}

After the first for loop, nums[i] is equal to the product of the numbers from 0 to i - 1. At each iteration of the second for loop, nums[i] is multiplied by the product of the numbers from i + 1 to len - 1. Therefore, after the two for loops, nums[i] = nums[0] * nums[1] * ... * nums[i-1] * ... * nums[i+1] * ... * nums[len-1].

Time Complexity: O(n)

Extra Space: O(1)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay