FastPrepProduct of Array Except Self

Product of Array Except Self

Walmart Labs logoWalmart Labs● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given nums, return an array whose element at index i is the product of every input element except nums[i]. Do not use division.

For this exercise, assume the product of an empty set is 1. Thus an empty input returns [], and a one-element input returns [1]. Zeros and negative values are allowed. Aim for linear time and constant auxiliary space excluding the returned array.

Function

productExceptSelf(nums: int[]) → int[]

Examples

Example 1

nums = [1,2,3,4]return = [24,12,8,6]

Four distinct positive factors.

Example 2

nums = [-1,1,0,-3,3]return = [0,0,9,0,0]

One zero with signed nonzero product.

Example 3

nums = []return = []

Empty array.

Constraints

  • 0 <= nums.length <= 100.
  • -10 <= nums[i] <= 10.
  • The product of the absolute values of all nonzero elements is at most 2^31 - 1; all intermediate and output products fit a signed 32-bit integer.

More Walmart Labs problems

See Walmart Labs hiring insights
public int[] productExceptSelf(int[] nums) {
    // Write your code here.
}
nums[1,2,3,4]
expected[24,12,8,6]
Checking account…