Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if subarray with given product exists in an array
Next article icon

Check if a Subarray exists with sums as a multiple of k

Last Updated : 27 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

Note: The length of the array won't exceed 10,000. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

Examples:

Input: [23, 2, 4, 6, 7], k = 6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

Input: [23, 2, 6, 4, 7], k = 6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is a continuous subarray of size 5 and sums up to 42.

Naive Approach: The basic way to solve the problem is as follows:

A straightforward way to tackle this problem is, by examining every subarray that has a size of least 2 and determining the sum of each one. If we find any subarray whose sum's divisible, by k we will answer with True; otherwise, we will respond with False.

Time Complexity: O(n^2) since there can be O(n^2) subarrays to evaluate.
Auxiliary Space: O(n^2)

Efficient Approach: To solve the problem follow the below idea:

The idea is to use a prefix sum array to keep track of the cumulative sum of the input array modulo k (i.e., the remainder after dividing by k). We'll also use a dictionary (hash map) to store the remainder values and their corresponding indices in the prefix sum array.

Follow the steps to solve the problem:

  • Initialize a prefix sum array presum with length n+1, where n is the length of the input array.
  • Initialize a dictionary seen to store the index of each remainder value.
  • Traverse the input array and compute the prefix sum array presum. For each prefix sum, compute presum[i] = (presum[i - 1] + arr[i - 1]) % k.
  • For each index i in the prefix sum array, check if the current remainder value presum[i] is already in the seen dictionary.
  • If it is, check if the distance between the current index i and the index stored in seen[presum[i]] is greater than 1. If yes, we found a subarray with a sum that is a multiple of k, so we return True.
  • If it's not in the dictionary, add the current remainder value presum[i] to the seen dictionary with the current index i.
  • If we have traversed the entire prefix sum array without finding a valid subarray, return False.

Dry Run:

Let's run through the examples you provided to understand how this approach works:

Input: nums = [23, 2, 4, 6, 7], k = 6

To start off we initialize a dictionary called "seen" with the key value pair of {0; 1}. Additionally, we set the prefix_sum" to zero.

Let's go through the elements:

  • Firstly, we process the number 23. Here's what happens.
    • We update the value of "prefix_sum" to be equal to 23.
    • Next, we calculate the residual by finding the remainder when dividing 23 by 6. In this case it is equal to 5. Since this residual (5) is not present in our "seen" dictionary yet we add it along with its corresponding index (0). So now our "seen" dictionary looks like this:
      {0: -1, 5: 0}.
  • Moving on to the element which's number 2
    • We update the value of "prefix_sum" by adding 2 to its current value of 23. Therefore, it becomes equal to 25.
    • Similar to before we calculate the residual by finding the remainder when dividing this prefix sum (25) by k (which's still equal to 6 in this case). The calculated residual turns out to be 1.
    • As for adding it into our "seen" dictionary since it's not present already. After doing our updated "seen" dictionary looks like this; {0: -1, 5:0, 1:1}.
  • Finally, we process the element which's number 4
    • Updating our prefix sum once again by adding 4 to its current value of 29 results in a new prefix sum of 33.
    • Calculating its corresponding residual using modulo operation with k (still being equal to six) gives us a value of 5.
    • However, this time we notice that the residual of 5 is already present in our "seen" dictionary at index 0. This means we have found a subarray [2, 4] whose sum adds up to be a multiple of k (which's six).
    • Therefore the output for this example is True.

Below is the implementation of above approach in python:

C++
#include <iostream> #include <unordered_map> #include <vector>  // Function to check if there exists a subarray with a sum divisible by k bool subarraySum(std::vector<int>& nums, int k) {     // Create a dictionary to store the residual values and their indices     std::unordered_map<int, int> seen;     seen[0] = -1;  // Initialize with a dummy value          int prefixSum = 0;  // Initialize the prefix sum          for (int i = 0; i < nums.size(); ++i) {         prefixSum += nums[i];  // Calculate the prefix sum         int residual = prefixSum % k;  // Calculate the residual value                  // If the same residual value has been seen before and the subarray size is at least 2         if (seen.find(residual) != seen.end() && i - seen[residual] > 1) {             return true;         }                  // If the residual value is not seen before, add it to the dictionary         if (seen.find(residual) == seen.end()) {             seen[residual] = i;         }     }          return false; }  int main() {     // Test cases     std::vector<int> nums1 = {23, 2, 4, 6, 7};     std::vector<int> nums2 = {23, 2, 6, 4, 7};          std::cout << std::boolalpha << subarraySum(nums1, 6) << std::endl;       std::cout << std::boolalpha << subarraySum(nums2, 6) << std::endl;            return 0; } 
Java
import java.util.HashMap;  public class Main {     public static boolean subarraySum(int[] nums, int k) {         // Create a dictionary to store the residual values and their indices         HashMap<Integer, Integer> seen = new HashMap<>();         seen.put(0, -1);  // Initialize with a dummy value                  int prefixSum = 0;  // Initialize the prefix sum                  for (int i = 0; i < nums.length; ++i) {             prefixSum += nums[i];  // Calculate the prefix sum             int residual = prefixSum % k;  // Calculate the residual value                          // If the same residual value has been seen before and the subarray size is at least 2             if (seen.containsKey(residual) && i - seen.get(residual) > 1) {                 return true;             }                          // If the residual value is not seen before, add it to the dictionary             if (!seen.containsKey(residual)) {                 seen.put(residual, i);             }         }                  return false;     }          public static void main(String[] args) {         // Test cases         int[] nums1 = {23, 2, 4, 6, 7};         int[] nums2 = {23, 2, 6, 4, 7};                  System.out.println(subarraySum(nums1, 6));           System.out.println(subarraySum(nums2, 6));       } } //Contributed by Aditi      
Python
# Python program for the above approach: def subarray_sum(nums, k):      # Create a dictionary to     # store the residual values     # and their indices     seen = {0: -1}      # Initialize the prefix sum     prefix_sum = 0      for i, num in enumerate(nums):         prefix_sum += num          # Calculate the residual value         residual = prefix_sum % k          # If the same residual value has been         # seen before and the subarray         # size is at least 2         if residual in seen and i - seen[residual] > 1:             return True          # If the residual value is         # not seen before,         # add it to the dictionary         if residual not in seen:             seen[residual] = i      return False   # Test cases print(subarray_sum([23, 2, 4, 6, 7], 6)) print(subarray_sum([23, 2, 6, 4, 7], 6)) 
C#
using System; using System.Collections.Generic;  class Program {       // Function to check if there exists a subarray with a sum divisible by k     static bool SubarraySum(List<int> nums, int k)     {               // Create a dictionary to store the residual values and their indices         Dictionary<int, int> seen = new Dictionary<int, int>();                  // Initialize with a dummy value         seen[0] = -1;                  // Initialize the prefix sum         int prefixSum = 0;         for (int i = 0; i < nums.Count; ++i)         {               // Calculate the prefix sum             prefixSum += nums[i];                          // Calculate the residual value             int residual = prefixSum % k;                      // If the same residual value has been seen before and the subarray size is at least 2             if (seen.ContainsKey(residual) && i - seen[residual] > 1)             {                 return true;             }                          // If the residual value is not seen before, add it to the dictionary             if (!seen.ContainsKey(residual))             {                 seen[residual] = i;             }         }         return false;     }        // Driver code      static void Main()     {         List<int> nums1 = new List<int> { 23, 2, 4, 6, 7 };         List<int> nums2 = new List<int> { 23, 2, 6, 4, 7 };         Console.WriteLine(SubarraySum(nums1, 6));         Console.WriteLine(SubarraySum(nums2, 6));     } } 
JavaScript
// JavaScript program for the above approach: function subarraySum(nums, k) {      // Create a map to store the residual values   // and their indices   let seen = new Map();      // Initialize the prefix sum   let prefixSum = 0;      for (let i = 0; i < nums.length; i++) {     prefixSum += nums[i];          // Calculate the residual value     let residual = prefixSum % k;          // If the same residual value has been     // seen before and the subarray     // size is at least 2     if (seen.has(residual) && i - seen.get(residual) > 1) {       return true;     }          // If the residual value is     // not seen before,     // add it to the map     if (!seen.has(residual)) {       seen.set(residual, i);     }   }      return false; }  // Test cases console.log(subarraySum([23, 2, 4, 6, 7], 6)); console.log(subarraySum([23, 2, 6, 4, 7], 6));  // This code is contributed by Sakshi 

Output
true true 

Time Complexity: O(n), where n is the length of the input array.
Auxiliary Space: O(min(n, k)), where n is the length of the input array and k is the target integer.


Next Article
Check if subarray with given product exists in an array
author
zaidkhan15
Improve
Article Tags :
  • DSA
  • Arrays
  • Facebook
  • prefix-sum
Practice Tags :
  • Facebook
  • Arrays
  • prefix-sum

Similar Reads

  • Check if a subarray exists with sum greater than the given Array
    Given an array of integers arr, the task is to check if there is a subarray (except the given array) such that the sum of its elements is greater than or equal to the sum of elements of the given array. If no such subarray is possible, print No, else print Yes.Examples: Input: arr = {5, 6, 7, 8} Out
    7 min read
  • Check if subarray with given product exists in an array
    Given an array of both positive and negative integers and a number K., The task is to check if any subarray with product K is present in the array or not. Examples: Input: arr[] = {-2, -1, 3, -4, 5}, K = 2Output: YESInput: arr[] = {3, -1, -1, -1, 5}, K = 3Output: YESApproach: The code provided seeks
    7 min read
  • Check if a subarray of length K with sum equal to factorial of a number exists or not
    Given an array arr[] of N integers and an integer K, the task is to find a subarray of length K with a sum of elements equal to factorial of any number. If no such subarray exists, print “-1”. Examples: Input: arr[] = {23, 45, 2, 4, 6, 9, 3, 32}, K = 5Output: 2 4 6 9 3Explanation:Subarray {2, 4, 6,
    12 min read
  • Count of subarrays with sum at least K
    Given an array arr[] of size N and an integer K > 0. The task is to find the number of subarrays with sum at least K.Examples: Input: arr[] = {6, 1, 2, 7}, K = 10 Output: 2 {6, 1, 2, 7} and {1, 2, 7} are the only valid subarrays.Input: arr[] = {3, 3, 3}, K = 5 Output: 3 Approach: For a fixed left
    6 min read
  • Smallest Subarray with Sum K from an Array
    Given an array arr[] consisting of N integers, the task is to find the length of the Smallest subarray with a sum equal to K. Examples: Input: arr[] = {2, 4, 6, 10, 2, 1}, K = 12 Output: 2 Explanation: All possible subarrays with sum 12 are {2, 4, 6} and {10, 2}. Input: arr[] = {-8, -8, -3, 8}, K =
    10 min read
  • Check if an array can be split into subarrays with GCD exceeding K
    Given an array arr[] of N integers and a positive integer K, the task is to check if it is possible to split this array into distinct contiguous subarrays such that the Greatest Common Divisor of all elements of each subarray is greater than K. Note: Each array element can be a part of exactly one s
    5 min read
  • Check if permutation of N exists with product of atleast 1 subarray's size and min as K
    Given two integers N and K, the task is to check if it is possible to form a permutation of N integers such that it contains atleast 1 subarray such that the product of length of that subarray with minimum element present in it is K. A permutation of size N have all the integers from 1 to N present
    7 min read
  • Check if it possible to partition in k subarrays with equal sum
    Given an array A of size N, and a number K. Task is to find out if it is possible to partition the array A into K contiguous subarrays such that the sum of elements within each of these subarrays is the same. Prerequisite: Count the number of ways to divide an array into three contiguous parts havin
    15+ min read
  • Count of subarrays which contains a given number exactly K times
    Given an array A[] of N elements consisting of values from 1 to N with duplicates, the task is to find the total number of subarrays that contain a given number num exactly K times. Examples: Input: A[] = {1, 2, 1, 5, 1}, num = 1, K = 2 Output: 2 Explanation: Subarrays {1, 2, 1, 5}, {1, 2, 1}, {2, 1
    8 min read
  • Smallest subarray whose sum is multiple of array size
    Given an array of size N, we need to find the smallest subarray whose sum is divisible by array size N. Examples : Input : arr[] = [1, 1, 2, 2, 4, 2] Output : [2 4] Size of array, N = 6 Following subarrays have sum as multiple of N [1, 1, 2, 2], [2, 4], [1, 1, 2, 2, 4, 2] The smallest among all is [
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences