Last updated on January 5th, 2025 at 12:37 am
Here, we see a Product of Array Except Self LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Array
Companies
Amazon, Apple, Facebook, LinkedIn, Microsoft
Level of Question
Medium
Product of Array Except Self LeetCode Solution
Table of Contents
1. Problem Statement
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]
2. Coding Pattern Used in Solution
The coding pattern used here is Prefix and Suffix Product. This pattern is useful for problems where you need to compute results based on cumulative operations (e.g., sums or products) from both directions of an array.
3. Code Implementation in Different Languages
3.1 Product of Array Except Self C++
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> output; for(int i=0; i<n; i++){ int product = 1; for(int j=0; j<n; j++){ if(i == j) continue; product *= nums[j]; } output.push_back(product); } return output; } };
3.2 Product of Array Except Self Java
class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int ans[] = new int[n]; for(int i = 0; i < n; i++) { int pro = 1; for(int j = 0; j < n; j++) { if(i == j) continue; pro *= nums[j]; } ans[i] = pro; } return ans; } }
3.3 Product of Array Except Self JavaScript
var productExceptSelf = function(nums) { const n = nums.length; const prefix = new Array(n).fill(1); const suffix = new Array(n).fill(1); for (let i = 1; i < n; i++) { prefix[i] = prefix[i - 1] * nums[i - 1]; } for (let i = n - 2; i >= 0; i--) { suffix[i] = suffix[i + 1] * nums[i + 1]; } const answer = []; for (let i = 0; i < n; i++) { answer[i] = prefix[i] * suffix[i]; } return answer; };
3.4 Product of Array Except Self Python
class Solution(object): def productExceptSelf(self, nums): n = len(nums) prefix = [1] * n suffix = [1] * n for i in range(1, n): prefix[i] = prefix[i - 1] * nums[i - 1] for i in range(n - 2, -1, -1): suffix[i] = suffix[i + 1] * nums[i + 1] answer = [prefix[i] * suffix[i] for i in range(n)] return answer
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n²) | O(n) |
Java | O(n²) | O(n) |
JavaScript | O(n) | O(n) |
Python | O(n²) | O(n) |