Product of Array Except Self

Returns a new array such that each index has the product of all elements except itself.

Medium

Examples

Example 1: [1,2,3,4] → [24,12,8,6]

Implementation

Ruby

  # ✖️ 5. Product of Array Except Self (prefix/suffix method)
  # Returns a new array such that each index has the product of all elements except itself.
  # Does not use division — builds prefix and suffix products in two passes.
  #
  # Time Complexity: O(n)
  # # Why: Two passes through the array — one forward, one backward — both linear.
  def product_except_self(nums)
    n = nums.length
    res = Array.new(n, 1)

    prefix = 1
    (0...n).each do |i|
      res[i] = prefix
      prefix *= nums[i]
    end

    suffix = 1
    (n - 1).downto(0) do |i|
      res[i] *= suffix
      suffix *= nums[i]
    end

    res

Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

Patterns & Techniques

Problem Details

Category: Array Hashing Examples
Difficulty: Medium
Module: ArrayHashingExamples
Method: product_except_self
← Back to Array Hashing Examples