Skip to main content

Command Palette

Search for a command to run...

product arrays itself

Published
1 min readView as Markdown
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;

        // Arrays to store prefix and suffix products
        int[] prefix = new int[n];
        int[] suffix = new int[n];
        int[] result = new int[n];

        // Build prefix product array
        prefix[0] = 1;
        for (int i = 1; i < n; i++) {
            prefix[i] = prefix[i - 1] * nums[i - 1];
        }

        // Build suffix product array
        suffix[n - 1] = 1;
        for (int i = n - 2; i >= 0; i--) {
            suffix[i] = suffix[i + 1] * nums[i + 1];
        }

        // Build result array by multiplying prefix and suffix
        for (int i = 0; i < n; i++) {
            result[i] = prefix[i] * suffix[i];
        }

        return result;
    }
}

More from this blog

Amit singh's blog

235 posts