Product of Array Except Self
You are given an array of integers nums. Your task is to construct an output array answer such that answer[i] equals the product of all the elements of nums except nums[i]. You must solve this without using division and in linear time complexity.
Imagine a factory where each worker represents a number and contributes to the total output. If one worker is missing, the factory’s output changes based on all the remaining workers. In this challenge, each position in the result array represents the factory’s output when one worker (the corresponding element) is left out. You must calculate these values efficiently without recalculating everything for each element.
The problem emphasizes reasoning about cumulative relationships between elements—how each value affects the whole. You are encouraged to think in terms of prefixes (products of elements before a given index) and suffixes (products after it) to achieve the correct result.
If the array has zeros, the result must handle them correctly: if there is one zero, all products except that index are zero; if there are multiple zeros, all results are zero.
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]
Example 3:
Input: nums = [2,3,4,5]
Output: [60,40,30,24]
Related Problems
No related problems found
Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
