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 — Basic Case
$ Input: nums = [23,2,4,6,7], k = 6
Output: true
💡 Note: Subarray [2,4] has sum 6, which is divisible by 6. Length is 2 ≥ 2, so it's a good subarray.
Example 2 — Multiple Elements
$ Input: nums = [23,2,4,6,6], k = 7
Output: true
💡 Note: Subarray [23,2,4,6] has sum 35, which is divisible by 7 (35 = 7 × 5). Length is 4 ≥ 2.
Example 3 — No Good Subarray
$ Input: nums = [23,2,4,6,6], k = 13
Output: false
💡 Note: No contiguous subarray of length ≥ 2 has a sum divisible by 13.

Constraints

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

Visualization

Tap to expand
INPUTALGORITHMRESULT232467k = 6Find subarray of length ≥ 2whose sum is divisible by 61Calculate prefix sums2Find remainder: sum % k3Track remainders in map4Same remainder = good subarrayFound: [2,4]Sum = 2 + 4 = 66 % 6 = 0 ✓Length = 2 ≥ 2 ✓Return trueKey Insight:If two prefix sums have the same remainder when divided by k, the subarray between them is divisible by kTutorialsPoint - Continuous Subarray Sum | Prefix Sum Approach
Asked in
Facebook 25 Google 18 Amazon 12 Apple 8
156.3K Views
Medium Frequency
~25 min Avg. Time
2.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