Compute product excluding index without division
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates array-manipulation and algorithmic problem-solving skills, focusing on computing a product-for-each-index using prefix and postfix accumulation concepts while reasoning about edge cases such as zeros, negative numbers, and integer overflow.
Constraints
- 2 <= nums.length <= 10^5
- -30 <= nums[i] <= 30
- The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
- You must NOT use the division operator
- O(n) time; O(1) extra space not counting the output array
Examples
Input: ([1, 2, 3, 4],)
Expected Output: [24, 12, 8, 6]
Explanation: ans[0]=2*3*4=24, ans[1]=1*3*4=12, ans[2]=1*2*4=8, ans[3]=1*2*3=6.
Input: ([-1, 1, 0, -3, 3],)
Expected Output: [0, 0, 9, 0, 0]
Explanation: Exactly one zero (at index 2): every other index includes that zero in its product and becomes 0; index 2 gets (-1)*1*(-3)*3 = 9.
Input: ([2, 3],)
Expected Output: [3, 2]
Explanation: Two-element array: ans[0] is the other element (3), ans[1] is the other element (2).
Input: ([5],)
Expected Output: [1]
Explanation: Single element boundary: there are no other elements, so the empty product is 1.
Input: ([0, 0, 4],)
Expected Output: [0, 0, 0]
Explanation: Two or more zeros: every output index still has at least one zero factor, so all entries are 0.
Input: ([-2, -3, -4],)
Expected Output: [12, 8, 6]
Explanation: All negatives: signs combine by multiplication. ans[0]=(-3)*(-4)=12, ans[1]=(-2)*(-4)=8, ans[2]=(-2)*(-3)=6.
Hints
- ans[i] = (product of everything to the LEFT of i) * (product of everything to the RIGHT of i). Compute each side with a single linear pass.
- Reuse the output array as scratch: first store the left/prefix products, then multiply in the right/postfix products on a second pass — that keeps extra space O(1).
- Carry one running accumulator per direction, initialized to 1. Multiply it by nums[i] AFTER writing it into ans[i] so the current element is excluded. Use a 64-bit accumulator to avoid intermediate overflow.