
- 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
Continuous Subarray Sum in C++
Suppose we have a list of non-negative numbers and a target integer k, we have to write a function to check whether the array has a continuous subarray of size at least 2 that sums up to a multiple of k, sums up to n*k where n is also an integer. So if the input is like [23,2,4,6,7], and k = 6, then the result will be True, as [2,4] is a continuous subarray of size 2 and sums up to 6.
To solve this, we will follow these steps −
- Make a map m, set m[0] := -1 and sum := 0, n := size of nums array
- for i in range 0 to n – 1
- sum := sum + nums[i]
- if k is non zero, then sum := sum mod k
- if m has sum, and i – m[sum] >= 2, then return true
- if m does not has sum, set m[sum] := i
- return false
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { unordered_map<int, int> m; m[0] = -1; int sum = 0; int n = nums.size(); for(int i = 0; i < n; i++){ sum += nums[i]; if(k) sum %= k; if(m.count(sum) && i - m[sum] >= 2){ return true; } if(!m.count(sum)) m[sum] = i; } return false; } }; main(){ vector<int> v = {23,2,4,6,7}; Solution ob; cout << (ob.checkSubarraySum(v, 6)); }
Input
[23,2,4,6,7] 6
Output
1
- Related Articles
- Shortest Unsorted Continuous Subarray in Python
- Subarray Sum Equals K in C++
- Minimum Size Subarray Sum in C++
- Maximum Sum Circular Subarray in C++
- Sum of Subarray Minimums in C++
- Maximum sum bitonic subarray in C++
- Maximum subarray sum modulo m in C++
- Maximum circular subarray sum in C++\n
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++
- Maximum subarray sum in O(n) using prefix sum in C++
- Find Maximum Sum Strictly Increasing Subarray in C++
- Maximum Subarray Sum with One Deletion in C++
- Maximum Subarray Sum Excluding Certain Elements in C++
- Maximum Size Subarray Sum Equals k in C++
- Maximum Subarray Sum in a given Range in C++

Advertisements