Continuous Subarray Sum - Problem

Given an integer array nums and an integer k, determine if there exists a good subarray within the array.

A good subarray must satisfy two conditions:

  • Its length is at least 2 (contains at least two elements)
  • The sum of its elements is a multiple of k

Key Points:

  • A subarray is a contiguous sequence of elements from the array
  • An integer x is a multiple of k if x = n ร— k for some integer n
  • 0 is always considered a multiple of any integer k

Return true if such a good subarray exists, otherwise return false.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [23,2,4,6,7], k = 6
โ€บ Output: true
๐Ÿ’ก Note: The subarray [2,4,6] has sum 12, which is divisible by 6 (12 = 2 ร— 6). The length is 3 โ‰ฅ 2, so this is a valid good subarray.
example_2.py โ€” No Valid Subarray
$ Input: nums = [23,2,4,6,6], k = 7
โ€บ Output: false
๐Ÿ’ก Note: No contiguous subarray of length โ‰ฅ 2 has a sum that is divisible by 7. We need to check all possible subarrays systematically.
example_3.py โ€” Edge Case with Zero
$ Input: nums = [5,0,0], k = 3
โ€บ Output: true
๐Ÿ’ก Note: The subarray [0,0] has sum 0, and 0 is always a multiple of any integer k. The length is 2 โ‰ฅ 2, making this a valid good subarray.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 0 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค 231 - 1
  • Subarray must have length โ‰ฅ 2

Visualization

Tap to expand
232467sum=23
rem=5sum=25
rem=1
sum=29
rem=5
sum=35
rem=5
sum=42
rem=0
Same remainder 5!Subarray [2,4,6] = 12 รท 6 = 0๐Ÿ’ก Key Insight: When prefix_sum % k repeats, the subarray between has sum divisible by k!If sum[0..i] โ‰ก sum[0..j] (mod k), then sum[i+1..j] โ‰ก 0 (mod k)This is because: sum[i+1..j] = sum[0..j] - sum[0..i]Continuous Subarray Sum - Prefix Sum Remainder Magic
Understanding the Visualization
1
Track Running Totals
Keep a running sum and calculate remainder when divided by k
2
Remember Patterns
Store each remainder and when we first saw it
3
Find Repeats
When we see the same remainder again, we found our answer!
4
Check Distance
Ensure the subarray has length โ‰ฅ 2 elements
Key Takeaway
๐ŸŽฏ Key Insight: The modular arithmetic approach transforms a seemingly complex problem into an elegant O(n) solution by recognizing that repeated remainders indicate divisible subarrays between them.
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
89.0K Views
High Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen