
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subarray Sum Equals K in C++
Suppose we have an array of integers and an integer k, we need to find the total number of continuous subarrays whose sum same as k. So if nums array is [1, 1, 1] and k is 2, then the output will be 2.
To solve this, we will follow these steps −
- define one map called sums, temp := 0, sums[0] := 1 and ans := 0
- for i in range 0 to size of the array
- temp := temp + n[i]
- if sums has k – temp, then
- ans := ans + sums[k - temp]
- increase the value of sums[-temp] by 1
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int subarraySum(vector<int>& n, int k) { unordered_map <int, int> sums; int temp = 0; sums[0] = 1; int ans =0; for(int i =0;i<n.size();i++){ temp+= n[i]; if(sums.find(k-temp)!=sums.end()){ ans += sums[k-temp]; } sums[-temp]++; } return ans; } }; main(){ Solution ob; vector<int> v = {1,1,1}; cout << (ob.subarraySum(v, 2)); }
Input
[1,1,1] 2
Output
2
Advertisements