Menu
CoddyTech

Product of Array Except Self

MediumPrefix sumpython iconjava iconcpp iconc iconjs icon+10

You get an array of integers nums. Return an array answer of the same length, where answer[i] is the product of every element of nums except the one at index i. Do it in O(n) time and without using division.

Function

productExceptSelf(nums: integer-array) → integer-array
numsinteger-array
the array of integers, with at least two elements
Returnsinteger-array
an array whose value at index i is the product of all elements except nums[i]

Constraints

  • 2 ≤ nums.length ≤ 104
  • -30 ≤ nums[i] ≤ 30
  • The product of all the nonzero values in nums fits in a 32-bit signed integer, so every product you build along the way fits too.

Examples

Input
nums = [2, 3, 4, 5]
Output
[60, 40, 30, 24]
Explanation
Leaving out the 2 leaves 3 × 4 × 5 = 60, and leaving out the 5 leaves 2 × 3 × 4 = 24. The middle two work the same way: 2 × 4 × 5 = 40 and 2 × 3 × 5 = 30.

lock icon+14 hidden tests on Submit

challenge icon

Follow-up

Can you use only O(1) extra space, not counting the array you return?

Reset code
def productExceptSelf(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [2, 3, 4, 5]

Expected

[60, 40, 30, 24]