Skip to content

Product of Array Except Self  #1

@cheatsheet1999

Description

@cheatsheet1999

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; };

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions