Subarray range with given sum | GeeksForGeeks | Problem of the Day

preview_player
Показать описание
Given an unsorted array of integers arr[], and a target tar, determine the number of subarrays whose elements sum up to the target value.

Examples:

Input: arr[] = [10, 2, -2, -20, 10] , tar = -10
Output: 3
Explanation: Subarrays with sum -10 are: [10, 2, -2, -20], [2, -2, -20, 10] and [-20, 10].
Input: arr[] = [1, 4, 20, 3, 10, 5] , tar = 33
Output: 1
Explanation: Subarray with sum 33 is: [20,3,10].
Expected Time Complexity: O(n)
Expected Auxilary Space: O(n)

#geeksforgeeks
#problemoftheday
#education
#computerscience
#coding
#array
#sorting
#sorts
#sort
#datastructure
#algorithmicproblemsolving
#algorithms
#algorithm
#dynamicprogramming
#dp
#potd
#gfg
#binarytree
#binarysearchtree
#bst
#string
#dictionary
#python
#stack
#queue
#python
#c++
#interview

Table of Contents
0:00 Problem Statement
0:29 Solution
7:51 Pseudo Code
9:36 Code - Python
10:18 Code - C++
Рекомендации по теме
Комментарии
Автор

Table of Contents
0:00 Problem Statement
0:29 Solution
7:51 Pseudo Code
9:36 Code - Python
10:18 Code - C++

mathematics
Автор

class Solution {
public:
// Function to count the number of subarrays which adds to the given sum.
int subArraySum(vector<int>& arr, int tar) {
map<int, int> mp;
mp[0] = 1;
int sum = 0, ans = 0;

for (const auto i: arr) {
sum += i;

//cout << "sum = " << sum << " looking for " << sum - tar << endl;
if (mp.find(sum - tar) != mp.end())
ans += mp[sum-tar];

mp[sum] += 1;
}

return ans;
}
};

mathematics
Автор

class Solution:

#Complete this fuction
#Function to count the number of subarrays which adds to the given sum.
def subArraySum(self, arr, tar):
mp = dict()
s = ans = 0
mp[0] = 1

for element in arr:
s += element

if s - tar in mp:
ans += mp[s-tar]

if s in mp:
mp[s] += 1
else:
mp[s] = 1

return ans

mathematics
Автор

Hey bud, if you dont mind can i get to know your LEETCODE and GFG handles, also want to know if you do CP and stuff?

mr.k
visit shbcf.ru