Compute Products Excluding Each Index
Company: Asana
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates array manipulation skills, arithmetic reasoning with cumulative products, edge-case handling for zeros and negative numbers, and time/space complexity optimization for in-place or constant-extra-space algorithms.
Constraints
- 0 <= n <= 100000
- -30 <= nums[i] <= 30
- Do not use division
- The final answers fit in a signed 64-bit integer
Examples
Input: ([1, 2, 3, 4],)
Expected Output: [24, 12, 8, 6]
Explanation: For each position, multiply all other values: 2*3*4=24, 1*3*4=12, 1*2*4=8, 1*2*3=6.
Input: ([-1, 2, -3, 4],)
Expected Output: [-24, 12, -8, 6]
Explanation: Negative numbers must be handled correctly: [2*(-3)*4, (-1)*(-3)*4, (-1)*2*4, (-1)*2*(-3)].
Input: ([0, 1, 2, 3],)
Expected Output: [6, 0, 0, 0]
Explanation: With exactly one zero, only the index containing zero gets the product of the non-zero elements. Every other index includes that zero, so its product is 0.
Input: ([0, 4, 0],)
Expected Output: [0, 0, 0]
Explanation: With more than one zero, every product excludes only one element but still includes at least one remaining zero.
Input: ([5],)
Expected Output: [1]
Explanation: There are no other elements, so the product of all elements except itself is the empty product, which is 1.
Input: ([],)
Expected Output: []
Explanation: An empty input has no indices, so the result is also an empty list.
Hints
- First store, for each index, the product of all numbers to its left.
- Then scan from right to left while keeping a running suffix product, and multiply it into the current answer.