Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Product of Array Except Self #1

Open
cheatsheet1999 opened this issue Sep 4, 2021 · 0 comments
Open

Product of Array Except Self #1

cheatsheet1999 opened this issue Sep 4, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

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]


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

Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]


It looks like we fliped the array, because we traverse from the back but get the result on the first index

  1. Traverse from right to left and we got...
    [24, 12, 4, 1]
  2. Traverse from the left to right, finally we got...
    [24, 12, 8, 6] leftMult was [1, 1, 2, 6]
var productExceptSelf = function(nums) {
    const res = [];
    let leftMult = 1;
    let rightMult = 1;
    for(let i = nums.length - 1; i >= 0; i--) {
        res[i] = rightMult;
        rightMult *= nums[i];
    }
    for(let i = 0; i < nums.length; i++) {
        res[i] *= leftMult;
        leftMult *= nums[i];
    }
    return res;
};
kyxg added a commit to kyxg/FrontEndCollection that referenced this issue Jan 4, 2022
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant