Product of All Other Elements for Each Index Without Division
Walmart LabsSoftware Engineer · OnsiteLast updated
For each position of an integer array, compute the product of all the other elements in linear time and without using division. It tests careful handling of zeros, negative values and repeated values, and planning a single efficient pass when the obvious division shortcut is not allowed.
Given an integer array nums, return an array answer of the same length in which answer[i] is the product of every element of nums except nums[i]. Do not use division, and run in time linear in the length of nums.
Function Signature
def products_except_self(nums: list[int]) -> list[int]:
Rules
answer[i]multiplies the elements at every index other thani, including any zeros among them.- Equal values are separate elements: leaving out
nums[i]removes only the element at indexi, not other elements with the same value. - Do not use the division operator anywhere in the computation.
- Return the products in index order, one per element of
nums.
Constraints
2 <= len(nums) <= 10^5-30 <= nums[i] <= 30- the product of every prefix of
nums, the product of every suffix ofnums, and every value ofanswerlie between-2^31and2^31 - 1
Examples
Example 1
Input: nums = [2, 3, 4, 5]
Output: [60, 40, 30, 24]
For example, answer[1] = 2 × 4 × 5 = 40.
Example 2
Input: nums = [-2, 0, 3, 1]
Output: [0, -6, 0, 0]
Only answer[1] leaves out the zero: (-2) × 3 × 1 = -6. Every other product includes it.
Example 3
Input: nums = [0, 4, 0]
Output: [0, 0, 0]
With two zeros, every product still includes at least one of them.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.