{"id":799,"date":"2023-12-07T17:00:00","date_gmt":"2023-12-07T17:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=799"},"modified":"2023-12-08T13:05:21","modified_gmt":"2023-12-08T13:05:21","slug":"subarray-sum-equals-k","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/subarray-sum-equals-k\/","title":{"rendered":"Subarray Sum Equals K (C++, Java, Python)"},"content":{"rendered":"\n<p>Arrays play a significant role in the world of programming and there are a lot of interview questions that depend on array data structure.  In this article, we will explore different approaches to solving the &#8216;subarray sum equals k&#8217; problem, starting with the brute force approach and gradually moving towards more efficient solutions using techniques of prefix sums.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Subarray Sum Equals K Problem?<\/strong><\/h2>\n\n\n\n<p>One particular problem that frequently arises is finding subarrays whose sum equals a given number, commonly referred to as the &#8220;subarray sum equals k&#8221; problem. This problem requires several subarrays with sum k where k is the given target. <\/p>\n\n\n\n<p><strong>In this problem, we are given an array and we have to tell the number of subarrays that sum equals k, a subarray is a contiguous subsequence of an array.<\/strong><\/p>\n\n\n\n<p>Let us understand it with an example:<\/p>\n\n\n\n<p class=\"has-black-color has-text-color has-background\" style=\"background-color:#fedcba\">Array = [1,2,3,2,1,4]<br>k = 5<br>Output = 3<\/p>\n\n\n\n<p>There are 3 subarrays, i.e. {2,3}, {3,2}, {1,4} whose element\u2019s sum is 5.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><img decoding=\"async\" width=\"1024\" height=\"483\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-1024x483.png\" alt=\"Example of Subarray Sum Equals K\" class=\"wp-image-803\" style=\"aspect-ratio:2.12008281573499;width:1024px;height:auto\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-1024x483.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-300x141.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-768x362.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-750x354.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5-1140x537.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/1-5.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Check out <a href=\"https:\/\/favtutor.com\/blogs\/kadanes-algorithm-python\">Kadane&#8217;s Algorithm<\/a> to learn how to find maximum sum subarray.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Brute Force Approach<\/strong><\/h2>\n\n\n\n<p>In the naive approach, we will generate all possible subarrays and check whether the sum of elements in the array is equal to k or not.<\/p>\n\n\n\n<p>Steps for brute force approach:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In this approach,\n<ul class=\"wp-block-list\">\n<li>we will use a nested loop to generate a subarray and inside this nested loop, we will run a loop for the sum of elements.<\/li>\n\n\n\n<li>We will initialize a count variable initially 0 to count the subarray with the given sum k.<br><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>We will run loop i from 0 to n-1 where n is the size of the array and inside it we will run a loop j from i to n-1.\n<ul class=\"wp-block-list\">\n<li>i denotes the starting index of the subarray and j denotes the ending index.<\/li>\n\n\n\n<li>We will add all the elements between index i and j including i,j using another loop.<br><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>When the subarray sum is equal to k we will increment the count variable.<br><\/li>\n<\/ul>\n\n\n\n<p>For the above example:<\/p>\n\n\n\n<p class=\"has-black-color has-text-color has-background\" style=\"background-color:#fedcba\">Array = [1,2,3,2,1,4]<br>k = 5<br>Output = 3<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The subarray with starting index i = 1 to ending index j = 2 has a sum equal to k.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"222\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-1024x222.png\" alt=\"subarray with i = 1 to j = 2\" class=\"wp-image-804\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-1024x222.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-300x65.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-768x166.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-750x162.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5-1140x247.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/2-5.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>The subarray with starting index i = 2 to ending index j = 3 has a sum equal to k.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"234\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-1024x234.png\" alt=\"subarray with i = 2 to j = 3\" class=\"wp-image-805\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-1024x234.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-300x68.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-768x175.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-750x171.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5-1140x260.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/3-5.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>The subarray with starting index i = 4 to ending index j = 5 has a sum equal to k.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"207\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-1024x207.png\" alt=\"subarray with i = 4 to j = 5\" class=\"wp-image-806\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-1024x207.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-300x61.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-768x155.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-750x151.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3-1140x230.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/4-3.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>The time complexity for the brute force approach is O(n<sup>3<\/sup>) because we are using a nested loop for finding the subarray with sum k and inside the nested loop there is another loop to sum all the elements of the subarray<\/p>\n\n\n\n<p>The space complexity for this approach is O(1) as we have not used any extra space&nbsp;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Optimized Approach: Using Prefix Sum<\/strong><\/h2>\n\n\n\n<p>In this approach, we will use the prefix sum technique to solve this problem. The prefix sum represents the cumulative sum up to the current index.<\/p>\n\n\n\n<p>Steps to solve the problem using the prefix sum approach:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Firstly we will declare a prefix_sum variable and a hashmap sum_count<br><\/li>\n\n\n\n<li>We will use a hashmap that stores the frequency of each prefix sum encountered so<br><\/li>\n\n\n\n<li>We will run a loop that iterates through the array, updating prefix_sum and checking if (prefix_sum &#8211; k) exists in sum_count.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"307\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-1024x307.png\" alt=\"prefix sum = 1\" class=\"wp-image-807\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-1024x307.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-300x90.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-768x230.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-750x225.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2-1140x341.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/7-2.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>The count is updated based on the frequency stored in sum_count<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"308\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-1024x308.png\" alt=\"prefix sum = 3\" class=\"wp-image-808\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-1024x308.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-300x90.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-768x231.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-750x226.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2-1140x343.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/8-2.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we obtain for index 2 prefix_sum = 6 and (prefix_sum &#8211; k) = 1 is already present in hashmap so 2,3 is one of our desired subarray<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"296\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-1024x296.png\" alt=\"prefix sum = 6\" class=\"wp-image-809\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-1024x296.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-300x87.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-768x222.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-750x217.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2-1140x330.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/12\/9-2.png 1279w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>We will repeat these steps for all indices and maintain a count that will count all these subarrays.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Below is the C++ solution for &#8216;Subrray Sum Equals K&#8217; problem:<\/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\nint subarraySum(vector&lt;int&gt;&amp; array, int k) {\n    int count = 0;\n    int prefix_Sum = 0;\n    unordered_map&lt;int, int&gt; sum_Count;\n    sum_Count[0] = 1;\n\n    for (int num : array) {\n        prefix_Sum += num;\n\n        \/\/ Check if (prefix_Sum - k) is in sum_Count\n        if (sum_Count.find(prefix_Sum - k) != sum_Count.end()) {\n            count += sum_Count[prefix_Sum - k];\n        }\n\n        \/\/ Update sumCount with the current prefixSum\n        sum_Count[prefix_Sum]++;\n    }\n\n    return count;\n}\n\nint main() {\n    vector&lt;int&gt; array = {1, 2, 3, 2, 1, 4};\n    int k = 5;\n    int result = subarraySum(array, k);\n\n   cout &lt;&lt; &quot;Number of subarrays with sum &quot; &lt;&lt; k &lt;&lt; &quot; = &quot; &lt;&lt; result &lt;&lt; endl;\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>You can use the prefix sum approach 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 subarray_sum(nums, k):\n    count = 0\n    prefix_sum = 0\n    sum_count = {0: 1}\n\n    for num in nums:\n        prefix_sum += num\n\n        # Check if (prefix_sum - k) is in sum_count\n        if prefix_sum - k in sum_count:\n            count += sum_count[prefix_sum - k]\n\n        # Update sum_count with the current prefix_sum\n        sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1\n\n    return count\n\nif __name__ == &quot;__main__&quot;:\n    array = [1, 2, 3, 2, 1, 4]\n    k = 5\n    result = subarray_sum(array, k)\n\n    print(f&quot;Number of subarrays with sum {k} = {result}&quot;)<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>Here is the Java program 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;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.HashMap;\nimport java.util.Map;\n\npublic class SubarraySum {\n\n    public static int subarraySum(int[] nums, int k) {\n        int count = 0;\n        int prefixSum = 0;\n        Map&lt;Integer, Integer&gt; sumCount = new HashMap&lt;&gt;();\n        sumCount.put(0, 1);\n\n        for (int num : nums) {\n            prefixSum += num;\n\n            \/\/ Check if (prefixSum - k) is in sumCount\n            if (sumCount.containsKey(prefixSum - k)) {\n                count += sumCount.get(prefixSum - k);\n            }\n\n            \/\/ Update sumCount with the current prefixSum\n            sumCount.put(prefixSum, sumCount.getOrDefault(prefixSum, 0) + 1);\n        }\n\n        return count;\n    }\n\n    public static void main(String[] args) {\n        int[] array = {1, 2, 3, 2, 1, 4};\n        int k = 5;\n        int result = subarraySum(array, k);\n\n        System.out.println(&quot;Number of subarrays with sum &quot; + k + &quot; = &quot; + result);\n    }\n}<\/pre><\/div>\n\n\n\n<p>The time complexity of this code is O(n), where n is the size of the input array. This is because the code iterates through the array once, and for each element, it performs constant-time operations (lookups and updates in the unordered_map).<\/p>\n\n\n\n<p>The space complexity is O(n) for the map data structure that we are using in this approach<\/p>\n\n\n\n<p>Here is a comparative analysis of both the approaches:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Approaches<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Time complexity<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Space complexity<\/strong><\/td><td><strong>Details<\/strong><\/td><\/tr><tr><td>Brute Force Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n<sup>3<\/sup>)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(1)<\/td><td>We are using a nested loop for finding the subarray with sum k and inside the nested loop there is another loop to sum all the elements of the subarray.<\/td><\/tr><tr><td>Prefix Sum Approach<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td class=\"has-text-align-center\" data-align=\"center\">O(n)<\/td><td>The code iterates through the array once, and for each element, it performs constant-time operations (lookups and updates in the unordered_map).<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In conclusion, the &#8220;subarray sum equals k&#8221; <a href=\"https:\/\/leetcode.com\/problems\/subarray-sum-equals-k\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode problem<\/a> is used to find the number of subarrays whose sum of elements is equal to the value k. It can be efficiently solved using the prefix sum approach, significantly improving the brute force approach. The prefix sum technique along with a hashmap to efficiently find subarrays with a sum equal to k. With the time complexity of O(n).<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will solve the leetcode problem called Subarray Sum equals K using brute force and prefix sum approaches.<\/p>\n","protected":false},"author":12,"featured_media":802,"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-799","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\/799","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=799"}],"version-history":[{"count":5,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/799\/revisions"}],"predecessor-version":[{"id":869,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/799\/revisions\/869"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/802"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=799"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=799"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=799"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}