{"id":1040,"date":"2023-12-17T13:00:00","date_gmt":"2023-12-17T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1040"},"modified":"2023-12-18T08:37:54","modified_gmt":"2023-12-18T08:37:54","slug":"product-of-array-except-itself","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/product-of-array-except-itself\/","title":{"rendered":"Find Product of Array Except Itself (C++, Java, Python)"},"content":{"rendered":"\n<p>Arrays are always the main data structures you need to master before coding interviews because there can be many interesting leetcode problems that you can have with it. In this article, we will explore one such problem to find the product of array except itself, find an optimal solution, and understand its time and space complexities.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Product of Array Except Self?<\/strong><\/h2>\n\n\n\n<p>Finding the Product of Array Except Itself which requires finding the product of all elements in an array, except for the element at a given index. Without the division operator, this problem can be solved efficiently in O(n) time. <\/p>\n\n\n\n<p>Here is the problem statement: <strong>&#8220;We are given an array of numbers, and for each element in the array, we need to find the product of all the other elements except itself.<\/strong>&#8220;<\/p>\n\n\n\n<p>Let us understand it better with an example:<\/p>\n\n\n\n<p>Numbers = [2,3,5,4,1]<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"201\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-1024x201.png\" alt=\"Example of Product of Array Except Self\" class=\"wp-image-1041\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-1024x201.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-300x59.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-768x151.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-750x147.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10-1140x224.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-10.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p><br>Output = [60,40,24,30,120]<\/p>\n\n\n\n<p>For the 0th index, the result will be the product of elements from index 1 to 4, i.e. 3*5*4*1 = 60. Similarly, it is calculated for the rest of the indexes.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"311\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-1024x311.png\" alt=\"Explanation of example\" class=\"wp-image-1042\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-1024x311.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-300x91.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-768x233.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-750x228.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14-1140x346.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-14.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>Using Prefix and Suffix Arrays to Solve this Problem<\/strong><\/h3>\n\n\n\n<p>In this approach, we will use a prefix and suffix array in a prefix array. We will maintain the product of the element of the array till that element from the start of the array for every element. In a suffix array, we will maintain the product of the element of the array till that element from the last of the array.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"218\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-1024x218.png\" alt=\"Prefix and Suffix Arrays\" class=\"wp-image-1043\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-1024x218.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-300x64.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-768x163.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-750x159.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4-1140x242.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-1-4.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Firstly we will fill the prefix array starting with initializing the first element of the prefix array as 1, as there are in the beginning there are no initial elements.&nbsp;<\/li>\n\n\n\n<li>Now we will iterate over the array starting from the second element and calculate the prefix product for that index.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" width=\"1024\" height=\"290\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-1024x290.png\" alt=\"calculate the prefix product\" class=\"wp-image-1044\" style=\"aspect-ratio:3.5310344827586206;width:1230px;height:auto\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-1024x290.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-300x85.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-768x217.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-750x212.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7-1140x323.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-7.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>After the prefix array, we will fill the suffix array starting with initializing the last element as 1, because there are no elements to the right.<\/li>\n\n\n\n<li>Now we will iterate over the array starting from the second last element to the first element and calculate the suffix product for that index.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" width=\"1024\" height=\"233\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-1024x233.png\" alt=\"calculate the suffix product\" class=\"wp-image-1045\" style=\"aspect-ratio:4.394849785407725;width:1362px;height:auto\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-1024x233.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-300x68.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-768x175.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-750x171.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3-1140x259.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/5-3.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>As we have calculated prefixes and suffixes for each index, the product of the prefix of an index and suffix of an index will give us the product of an array except that element.<\/li>\n\n\n\n<li>Now we will iterate over the prefix array and suffix array and find the product of the array for every element except that current element.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" width=\"1024\" height=\"347\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-1024x347.png\" alt=\"find the product of the array for every element\" class=\"wp-image-1047\" style=\"aspect-ratio:2.951008645533141;width:1298px;height:auto\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-1024x347.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-300x102.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-768x260.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-750x254.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2-1140x387.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/6-2.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to find the product of array except itself:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\nvector&lt;int&gt; productExceptSelf(vector&lt;int&gt;&amp; nums) {\n    int n = nums.size();\n    \n    \/\/ Initialize arrays to store prefix and suffix products\n    vector&lt;int&gt; prefix(n, 1);  \/\/ Prefix product of elements to the left\n    vector&lt;int&gt; suffix(n, 1);  \/\/ Suffix product of elements to the right\n    vector&lt;int&gt; prod(n);       \/\/ Final product array\n\n    \/\/ Calculate prefix products\n    for (int i = 1; i &lt; n; i++) {\n        prefix[i] = prefix[i - 1] * nums[i - 1];\n    }\n\n    \/\/ Calculate suffix products\n    for (int i = n - 2; i &gt;= 0; i--) {\n        suffix[i] = suffix[i + 1] * nums[i + 1];\n    }\n\n    \/\/ Calculate the final product array\n    for (int i = 0; i &lt; n; i++) {\n        prod[i] = prefix[i] * suffix[i];\n    }\n\n    return prod;\n}\n\nint main() {\n    vector&lt;int&gt; nums = {2, 3, 5, 4, 1};\n    vector&lt;int&gt; prod = productExceptSelf(nums);\n\n    cout &lt;&lt; &quot;The product array is: &quot;;\n    for (int num : prod) {\n        cout &lt;&lt; num &lt;&lt; &quot; &quot;;\n    }\n    cout &lt;&lt; endl;\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Below is the Java program to solve it:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.Arrays;\n\npublic class ProductExceptSelf {\n    public static int[] productExceptSelf(int[] nums) {\n        int n = nums.length;\n\n        \/\/ Initialize arrays to store prefix and suffix products\n        int[] prefix = new int[n];  \/\/ Prefix product of elements to the left\n        int[] suffix = new int[n];  \/\/ Suffix product of elements to the right\n        int[] prod = new int[n];    \/\/ Final product array\n\n        \/\/ Calculate prefix products\n        prefix[0] = 1;\n        for (int i = 1; i &lt; n; i++) {\n            prefix[i] = prefix[i - 1] * nums[i - 1];\n        }\n\n        \/\/ Calculate suffix products\n        suffix[n - 1] = 1;\n        for (int i = n - 2; i &gt;= 0; i--) {\n            suffix[i] = suffix[i + 1] * nums[i + 1];\n        }\n\n        \/\/ Calculate the final product array\n        for (int i = 0; i &lt; n; i++) {\n            prod[i] = prefix[i] * suffix[i];\n        }\n\n        return prod;\n    }\n\n    public static void main(String[] args) {\n        int[] nums = {2, 3, 5, 4, 1};\n        int[] prod = productExceptSelf(nums);\n\n        System.out.print(&quot;The product array is: &quot;);\n        System.out.println(Arrays.toString(prod));\n    }\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the implementation in Python as well:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">def product_except_self(nums):\n    n = len(nums)\n    \n    # Initialize arrays to store prefix and suffix products\n    prefix = [1] * n  # Prefix product of elements to the left\n    suffix = [1] * n  # Suffix product of elements to the right\n    prod = [0] * n    # Final product array\n\n    # Calculate prefix products\n    for i in range(1, n):\n        prefix[i] = prefix[i - 1] * nums[i - 1]\n\n    # Calculate suffix products\n    for i in range(n - 2, -1, -1):\n        suffix[i] = suffix[i + 1] * nums[i + 1]\n\n    # Calculate the final product array\n    for i in range(n):\n        prod[i] = prefix[i] * suffix[i]\n\n    return prod\n\nnums = [2, 3, 5, 4, 1]\nprod = product_except_self(nums)\n\nprint(&quot;The product array is:&quot;, prod)<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>The product array is: &#91;60, 40, 24, 30, 120]<\/code><\/pre>\n\n\n\n<p>The time complexity of this approach is O(n) as Calculating the prefix array takes O(n) time, where n is the size of the input array, Calculating the suffix array also takes O(n) time, calculating the product of prefix[i] * sufix[i] array takes O(n) time. So The overall time complexity is O(n).<\/p>\n\n\n\n<p>The space complexity of this approach is O(n)+O(n) as we are using prefix array and suffix array of size n where n is the size of the given array.<\/p>\n\n\n\n<p>Now, you can solve another problem called <a href=\"https:\/\/favtutor.com\/articles\/subarray-sum-equals-k\/\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/articles\/subarray-sum-equals-k\/\">Subarray Sum Equals K<\/a>, which is also asked a lot in interviews.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In this article, we have discussed an optimized approach to solve this unique <a href=\"https:\/\/leetcode.com\/problems\/product-of-array-except-self\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode problem<\/a> to find the product of array except itself. Using prefix and suffix array limits the time complexity to O(n) without using the division operator<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will solve the leetcode programming problem to find the product of array except itself using prefix and suffix arrays<\/p>\n","protected":false},"author":12,"featured_media":1049,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1040","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1040","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1040"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1040\/revisions"}],"predecessor-version":[{"id":1087,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1040\/revisions\/1087"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1049"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1040"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1040"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1040"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}