Arrays and Hashing Prefix sums

73. Product of Array Except Self

Medium 147 DSA Sheet

You are given 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 nums[i].

"Except nums[i]" means except the element at position i. If the same value appears at another position, that copy is still multiplied in.

Example 1

Input: nums = [2, 3, 4, 5]

Output: [60,40,30,24]

Explanation: answer[0] is 3 × 4 × 5 = 60, answer[1] is 2 × 4 × 5 = 40, answer[2] is 2 × 3 × 5 = 30 and answer[3] is 2 × 3 × 4 = 24.

Example 2

Input: nums = [-1, 2, 0, 4]

Output: [0,0,-8,0]

Explanation: Every product that includes the 0 is 0. Only answer[2] leaves the 0 out, and it is −1 × 2 × 4 = −8.

Example 3

Input: nums = [100000, 100000, 3]

Output: [300000,300000,10000000000]

Explanation: answer[2] is 100000 × 100000 = 1010, which is more than a 32-bit integer can hold.

Check your understanding

Work out the answer for this input before you write any code.

nums = [2, 0, 3]

Constraints

  • 2 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • The product of any set of elements of nums fits in a signed 64-bit integer.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.