FrontendInterviews.dev

Loading problem…

95. Product of Array Except Self - Recommendation Algorithm

Medium•
Acceptance: 93.33%
•
🔓3/3 Pro unlocks today

You're building a recommendation algorithm for an e-commerce platform. For each product, you need to calculate a recommendation score based on the product of all other products' ratings, excluding the current product. This helps generate "customers who bought this also bought" suggestions.

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 operator.

Requirements

1. Basic Functionality

  • Calculate product of all elements except current
  • Return array of products
  • O(n) time complexity
  • No division operator allowed
  • O(1) extra space (excluding output array)

Example Usage

productExceptSelf([1,2,3,4]); // [24,12,8,6]
// For index 0: 2*3*4 = 24
// For index 1: 1*3*4 = 12
// For index 2: 1*2*4 = 8
// For index 3: 1*2*3 = 6

productExceptSelf([-1,1,0,-3,3]); // [0,0,9,0,0]

Real-World Context

This problem models real recommendation systems:

  • Product recommendations: Calculate scores based on other products
  • Analytics calculations: Compute metrics excluding current item
  • Rating systems: Generate recommendations from user ratings
  • Statistical analysis: Calculate products for data analysis

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
  • Must be O(n) time, O(1) extra space
  • No division operator