DSA Problems/πŸ“ŠArrays & Hashing

Product of Array Except Self

ArrayPrefix Sum

Problem Statement

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all elements of nums except nums[i].

You must solve it without using division and in O(n) time.

Approach

Use prefix and suffix products. First pass computes prefix products, second pass multiplies by suffix products.

Complexity Analysis

MetricValue
TimeO(n)
SpaceO(1) excluding output

Examples

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]

Constraints

  • β–Έ2 <= nums.length <= 10^5
  • β–Έ-30 <= nums[i] <= 30
  • β–ΈThe product of any prefix or suffix fits in a 32-bit integer
Loading...
Sign in to run your code...

Asked by companies:

AmazonFacebookAppleMicrosoft