AlgoInsight

DSA problem

Continuous Subarray Sum

MediumPrefix SumPattern: Prefix Sum + Hash Maptop300FacebookAmazonMicrosoftGoogle

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 multiple of k is any integer n * k where n is an integer, so 0 is always considered a multiple of k.

The trick is the same congruence idea used to count divisible subarrays: if two prefix sums leave the same remainder modulo k, the subarray between them sums to a multiple of k. To enforce the minimum length of two, we store the earliest index at which each remainder first appeared and only accept a match when the current index is at least two positions later.

Examples

Example 1
Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: The subarray [2,4] has length 2 and sums to 6, which is a multiple of 6.
Example 2
Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: The entire array [23,2,6,4,7] has length 5 and sums to 42, which is 7 * 6, a multiple of 6.
Example 3
Input: nums = [23,2,6,4,7], k = 13
Output: false
Explanation: No subarray of length at least 2 sums to a multiple of 13.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

prefix-sumhash-maparraymath

Browse all DSA problems