
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Maximum Size Subarray Sum Equals k in C++
- Shortest Subarray with Sum at Least K in C++
- Largest subarray having sum greater than k in C++
- Largest sum subarray with at-least k numbers in C++
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Find maximum (or minimum) sum of a subarray of size k in C++
- Maximum subarray sum by flipping signs of at most K array elements in C++
- Maximum subarray sum in array formed by repeating the given array k times in C++
- Continuous Subarray Sum in C++
- Subarray Product Less Than K in C++
- Subarray Sums Divisible by K in C++
- Largest Sum Contiguous Subarray
- Minimum Size Subarray Sum in C++
- Maximum Sum Circular Subarray in C++
- Sum of Subarray Minimums in C++

Advertisements