Skip to main content

Continuous Subarray Sum - Solution & Explanation

MediumArrayHash TableMathPrefix Sum22 min readAsked at: Amazon, Microsoft, Apple +6
Practice this problem

Problem Statement

Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

A good subarray is a subarray where:

  • its length is at least two, and
  • the sum of the elements of the subarray is a multiple of k.

Note that:

  • A subarray is a contiguous part of the array.
  • An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k.

 

Example 1:

Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.

Example 2:

Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.

Example 3:

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

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 0 <= sum(nums[i]) <= 231 - 1
  • 1 <= k <= 231 - 1

Approach Overview

Problem Overview: Given an integer array nums and an integer k, determine whether the array contains a continuous subarray of at least length 2 whose total sum is a multiple of k. In other words, check if there exist indices i < j such that the sum of elements from i to j is divisible by k.

Approach 1: Iterative Brute Force (Naive Approach) (Time: O(n²), Space: O(1))

Start from each index i and iteratively expand the subarray by adding elements nums[j]. Maintain a running sum while extending the window. After every extension where the subarray length is at least 2, check if sum % k == 0. This approach directly tests all possible subarrays of length ≥2. It works but quickly becomes slow for large arrays because the number of subarrays grows quadratically. It’s mainly useful for understanding the problem or validating small inputs.

Approach 2: Prefix Sum with Modulo and HashMap (Time: O(n), Space: O(n))

The key observation comes from modular arithmetic. If two prefix sums have the same remainder when divided by k, the subarray between them must sum to a multiple of k. While iterating through the array, compute a running prefix sum and store prefixSum % k in a hash map along with the earliest index where that remainder appeared. When the same remainder appears again, check if the distance between indices is at least 2. If it is, a valid subarray exists.

The hash map stores remainder → first index. Initialize it with 0 → -1 so that a valid subarray starting from index 0 can be detected. For each element, update the running sum, compute the remainder, and check if that remainder already exists in the map. If it does and the index difference is greater than 1, return true. Otherwise store the remainder if it hasn't appeared before. This method reduces the search from checking all subarrays to a single pass using a hash table.

This technique relies on prefix sums and modular arithmetic, both common patterns when working with cumulative ranges in an array. Handling k = 0 requires checking for consecutive zeros because modulo with zero is undefined.

Recommended for interviews: Interviewers expect the prefix sum + modulo hash map solution. The brute force approach demonstrates understanding of the problem but does not scale. Recognizing the repeated remainder pattern and converting the problem into a prefix remainder lookup shows strong problem‑solving and familiarity with common interview patterns.

Approach 1: Prefix Sum with Modulo and HashMap

The idea is to use a running or cumulative sum and check the remainder when this sum is divided by k. If any two prefix sums have the same remainder, the subarray sum between these indices is divisible by k.

We maintain a hashmap to store each remainder and its index. As we iterate over the array, we update the running sum and check its remainder. If the remainder has been seen before and the subarray length is at least 2, we return true. If not, we continue. If we finish the loop without finding such a subarray, we return false.

In this C implementation, we use a dynamically allocated array to simulate a hashmap. We initialize all elements to -1, except the zero remainder, which is initialized to index 0 to handle the case where a subarray from the start has a sum that is a multiple of k.

The main loop updates the cumulative sum, calculates its modulo with k, and checks if this remainder was seen before in the hashmap, with the appropriate handling for negative mod cases. If so and the subarray has at least length 2, it returns true. Otherwise, it logs the index of this new remainder.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of nums, since we iterate over the array only once.

Space Complexity: O(k), as we use a hashmap (or array) to store remainders which can be 0 through k-1 in the worst case.

Try this approach in the editor →

Approach 2: Iterative Brute Force (Naive Approach)

This approach attempts every possible subarray of length at least 2, calculating the sum for each and checking if it is a multiple of k. Although not efficient, this serves as a basic solution for smaller inputs.

The process involves iterating over each possible starting point of a subarray, then for each starting point, iterating over each possible ending point to compute the sum, subsequently verifying its divisibility by k.

This brute force approach implemented in C checks all subarrays of length at least 2. It attempts every start position and iterates all feasible end positions to compute subarray sum and verify divisibility by k.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n²) because of the nested loop structure iterating through potential subarray limits.

Space Complexity: O(1) as no extra space apart from a few variables is used.

Try this approach in the editor →

Approach 3: Prefix Sum + Hash Table

According to the problem description, if there exist two positions i and j (j < i) where the remainders of the prefix sums modulo k are the same, then the sum of the subarray nums[j+1..i] is a multiple of k.

Therefore, we can use a hash table to store the first occurrence of each remainder of the prefix sum modulo k. Initially, we store a key-value pair (0, -1) in the hash table, indicating that the remainder 0 of the prefix sum 0 appears at position -1.

As we iterate through the array, we calculate the current prefix sum's remainder modulo k. If the current prefix sum's remainder modulo k has not appeared in the hash table, we store the current prefix sum's remainder modulo k and its corresponding position in the hash table. Otherwise, if the current prefix sum's remainder modulo k has already appeared in the hash table at position j, then we have found a subarray nums[j+1..i] that meets the conditions, and thus return True.

After completing the iteration, if no subarray meeting the conditions is found, we return False.

The time complexity is O(n), and the space complexity is O(n), where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Prefix Sum with Modulo and HashMap

Time Complexity: O(n), where n is the length of nums, since we iterate over the array only once.

Space Complexity: O(k), as we use a hashmap (or array) to store remainders which can be 0 through k-1 in the worst case.

Iterative Brute Force (Naive Approach)

Time Complexity: O(n²) because of the nested loop structure iterating through potential subarray limits.

Space Complexity: O(1) as no extra space apart from a few variables is used.

Prefix Sum + Hash Table

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Iterative Brute ForceO(n²)O(1)Good for understanding the problem or verifying logic on small inputs
Prefix Sum with Modulo + HashMapO(n)O(n)Optimal approach for interviews and large arrays

Video Solution

Continuous Subarray Sum - Leetcode 523 - PythonNeetCode101,262 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Continuous Subarray Sum easy or hard?
Continuous Subarray Sum is classified as a medium difficulty problem. The brute force idea is straightforward, but identifying the prefix sum modulo pattern and implementing the hash map optimization requires familiarity with common interview techniques.
How to solve Continuous Subarray Sum in O(n)?
Maintain a running prefix sum while iterating through the array. Compute the remainder of the prefix sum with k and store the first occurrence of each remainder in a hash map. When the same remainder appears again and the gap between indices is at least two, a valid subarray exists. This avoids checking every subarray explicitly.
What is the best approach for Continuous Subarray Sum?
The optimal approach uses prefix sum with modulo and a hash map. While iterating through the array, store the first index where each remainder (prefixSum % k) appears. If the same remainder appears again and the index difference is at least 2, the subarray between them has a sum divisible by k. This solution runs in O(n) time with O(n) space.
What data structure is used in Continuous Subarray Sum?
The optimal solution relies on a hash map to store the earliest index for each prefix sum remainder. Combined with a running prefix sum and modulo arithmetic, the hash map allows constant-time checks to determine whether a valid subarray exists.
What is the time complexity of Continuous Subarray Sum?
The optimal prefix sum and hash map solution runs in O(n) time because the array is scanned once and each hash lookup is O(1) on average. Space complexity is O(n) for storing remainders. The brute force approach takes O(n²) time since it checks every possible subarray.
Continuous Subarray Sum Python or Java solution approach?
Both Python and Java implementations follow the same logic: compute a running prefix sum, track prefixSum % k, and store the earliest index of each remainder in a hash map. When the same remainder reappears with an index gap of at least two, return true. The complexity remains O(n) time and O(n) space.
Is Continuous Subarray Sum asked at Google, Amazon, or Meta?
Continuous Subarray Sum is a common medium-level interview problem and appears in question banks used by companies like Amazon, Google, and Meta. It tests knowledge of prefix sums, modular arithmetic, and hash maps—patterns frequently evaluated in coding interviews.

Ready to solve this problem?

Practice Continuous Subarray Sum with our built-in code editor and test cases.

Practice on FleetCode