Taro Logo

Product of Array Except Self

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+32
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.3K views
Topics:
Arrays

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

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]

Constraints:

  • 2 <= nums.length <= 105
  • -30 <= nums[i] <= 30
  • The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the size of the input array `nums` and the range of values each element can take?
  2. How should we handle edge cases like an empty array or an array with only a single element?
  3. Can the input array contain negative numbers and zeros, and how should multiple zeros in the array affect the output products?
  4. Should the result be returned as a brand new array, or are we expected to modify the input array in place to save memory?
  5. Since the problem states we cannot use the division operator, is there any restriction on using auxiliary space (like creating extra arrays), or is $O(1)$ extra space (excluding the output array) expected?

Brute Force Solution

Approach

Imagine you are given a row of items, and for every single item, you need to calculate the combined value of all the other items around it combined together. The brute force approach achieves this by looking at every item one by one and manually multiplying all the other items from scratch.

Here's how the algorithm would work step-by-step:

  1. Start by focusing on the very first item in the row.
  2. Gather every single other item that is not the one you are currently focusing on.
  3. Multiply all of those gathered items together to find the final combined value for this specific item.
  4. Write down this result and set it aside.
  5. Move your focus to the next item in the row and repeat the entire process of gathering all the remaining items.
  6. Multiply all those newly gathered items together and record that result.
  7. Continue this exact same process for every single item in the row until every item has its own calculated combined value.

Code Implementation

def product_except_self_brute_force(input_numbers):
    # We need a container to store the calculated product for each item
    result_collection = []

    # Iterate through every single item to compute its exclusive product
    for target_index in range(len(input_numbers)):
        current_product = 1

        # Gather and multiply all other items except the current target
        for other_index in range(len(input_numbers)):
            if target_index != other_index:
                current_product *= input_numbers[other_index]

        # Append the final combined product for the current item
        result_collection.append(current_product)

    return result_collection

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the row, we loop through and gather every single other item to multiply them together from scratch. For the first item, we process (n-1) elements, for the second item we process (n-1) elements, and we repeat this complete gathering process for all n items. This nested iteration leads to approximately n * n operations, which simplifies to O(n²).
Space Complexity
O(1) – When executing the brute force approach described, we only use a few primitive variables to keep track of the current item and running products, requiring no auxiliary data structures. The output array itself is expected by the problem statement and does not count toward auxiliary space. Therefore, the extra memory used remains constant regardless of the input size N.

Optimal Solution

Approach

To find the product of all items except the current one without using division, we can break the task into two passes. The strategy involves looking at everything to the left and everything to the right of each item, then combining those two perspectives.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the line of items from left to right, and for each item, calculate the combined product of everything sitting strictly to its left.
  2. Record these running left-side products for each position so you know what is happening before each item.
  3. Next, reverse direction and look at the line from right to left, keeping a running product of everything sitting strictly to the right of each item.
  4. As you move right to left, multiply the running right-side product with the previously recorded left-side product for that exact position.
  5. Place this final combined result into the final answer spot for that item, representing the product of everything except the item itself.

Code Implementation

def product_except_self(input_numbers):
    array_length = len(input_numbers)
    output_result = [1] * array_length

    # We accumulate left products first so each position knows what precedes it.
    running_left_product = 1
    for index_value in range(array_length):
        output_result[index_value] = running_left_product
        running_left_product *= input_numbers[index_value]

    # Multiplying by right products combines both sides without using division.
    running_right_product = 1
    for index_value in range(array_length - 1, -1, -1):
        output_result[index_value] *= running_right_product
        running_right_product *= input_numbers[index_value]

    # The final array now contains the complete product of all elements except self.
    return output_result

Big(O) Analysis

Time Complexity
O(n) – The algorithm processes the array of size n through two distinct sequential passes. First, a left-to-right pass calculates the running product of elements strictly to the left for each of the n items. Second, a right-to-left pass computes the running product of elements strictly to the right and multiplies it by the stored left-side product. Because these operations occur in two independent linear traversals rather than nested iterations, the total workload approximates 2n operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm records the running left-side products directly into the final output array and uses a single integer variable to track the running right-side product during the second pass. Since the output array is excluded from auxiliary space calculations according to standard conventions, the only extra memory consumed is for a constant number of primitive variables. As the input size N grows, these scalar variables do not scale, meaning no additional data structures of size N are created. Therefore, the auxiliary space complexity simplifies to O(1).

Edge Cases

Array containing a single zero
How to Handle:
The prefix and suffix multiplication passes naturally compute the correct product of one for that single element.
Array containing multiple zeros
How to Handle:
Once there are two or more zeros in the array, all products in the resulting array will correctly evaluate to zero.
Array containing a single negative number or all negative numbers
How to Handle:
The multiplication logic accumulates signs correctly through the prefix and suffix passes to yield the proper positive or negative products.
Minimum valid input array of size two
How to Handle:
The prefix pass will be empty for the first element and the suffix pass will be empty for the second, resulting in the correct swapped pair.
Maximum constraint array size up to one hundred thousand elements
How to Handle:
The linear time O(n) approach ensures the solution executes well within standard interview time limits without hitting timeout errors.
Large integers causing integer overflow during multiplication
How to Handle:
Since constraints typically guarantee fits within standard integer ranges or the problem implies standard 32-bit integers, standard multiplication is assumed sufficient unless language-specific wrapping occurs.
Array with all identical non-zero values
How to Handle:
The prefix and suffix products calculate powers of that value, resulting in each position holding the value raised to the power of n minus one.
Array containing a single zero at the beginning or end
How to Handle:
The zero will propagate its effect to all other indices while the zero index itself receives the full product of all non-zero elements.
0/75 completed