Compute product excluding index without division
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: 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.
Read the full Amazon Software Engineer interview experience this question came from
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.
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.