Continuous Subarray Sum - Problem

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
  • 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

Input & Output

Example 1 — Valid Subarray Found
$ Input: nums = [23,2,4,6,7], k = 6
Output: true
💡 Note: The subarray [2,4] has sum 6, which is divisible by 6. Also [4,6] has sum 10... wait, let me recalculate: [2,4] = 6, [4,6] = 10, [6,7] = 13. Actually [2,4] with sum 6 is divisible by 6, so return true.
Example 2 — No Valid Subarray
$ Input: nums = [23,2,4,6,6], k = 7
Output: false
💡 Note: No subarray of length ≥ 2 has sum divisible by 7. Checking: [23,2]=25, [2,4]=6, [4,6]=10, [6,6]=12, [23,2,4]=29, etc. None are divisible by 7.
Example 3 — Zero Sum Edge Case
$ 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 k. Length is 2, so this is valid.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 231 - 1

Visualization

Tap to expand
Continuous Subarray Sum: Find subarray with sum divisible by kInput: nums = [23,2,4,6,7], k = 6232467Subarray [2,4]Sum = 2 + 4 = 66 ÷ 6 = 1 (divisible)Process: Check all subarrays of length ≥ 2Goal: Find sum that is multiple of kOutput: true
Understanding the Visualization
1
Input
Array [23,2,4,6,7] and divisor k=6
2
Process
Check subarrays for sum divisibility
3
Output
Return true if valid subarray exists
Key Takeaway
🎯 Key Insight: Use modular arithmetic with hash map to detect when prefix sum remainders repeat
Asked in
Facebook 45 Google 38 Amazon 32 Microsoft 28
285.0K Views
High Frequency
~25 min Avg. Time
3.8K 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