Skip to content
Problem 523 · LeetCode 523(opens in a new tab)

Continuous Subarray Sum

MediumArrays

You are given an array of non-negative whole numbers, nums, and a positive whole number k.

Return true if some run of at least two neighbouring elements adds up to a multiple of k, and false otherwise. A sum of 0 counts as a multiple of every k.

Example 1

Input:  nums = [2, 7, 3, 6, 4], k = 8
Output: true
Why:    7 + 3 + 6 = 16, which is 2 × 8
2 more examples and the constraints

Example 2

Input:  nums = [5, 0, 0], k = 3
Output: true
Why:    0 + 0 = 0, and 0 is a multiple of 3

Example 3

Input:  nums = [1, 6], k = 6
Output: false
Why:    6 alone is too short, and 1 + 6 = 7

Constraints

  • 1 ≤ length of nums ≤ 100,000
  • 0 ≤ nums[i] ≤ 1,000,000,000, and the whole array sums to at most 2³¹ − 1
  • 1 ≤ k ≤ 2³¹ − 1

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every start, grow the endO(n²)
  2. Prefix remaindersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Every start, grow the endO(n²)
Mention it, then move on
Prefix remaindersO(n)
Best; one pass

n = length of nums, k = the divisor.

Edge cases to test

  • Two zeros in a row. [5, 0, 0] with any k is true: 0 + 0 = 0 is a multiple of everything.
  • One good number alone. [1, 6] with k = 6 is false; a single element does not count.
  • Only one number. [6] is always false, since no run has two elements.
  • k = 1. Every sum is a multiple of 1, so any array of length 2 or more is true.
  • Whole array is the answer. The stored −1 for remainder 0 lets a run start at position 0.

Common mistakes

  • Forgetting the seed 0 → −1, which misses good runs that start at position 0.
  • Overwriting the stored index with a newer one, which turns valid long runs into too-short ones.
  • Allowing runs of length 1, so [1, 6] with k = 6 wrongly returns true.

How to talk through it

  1. 1Clarify. Must the run have at least two elements? Does 0 count as a multiple of k? Can values be negative?
  2. 2Give the brute force. Every start with a running total: O(n²), too slow for 100,000 numbers.
  3. 3Use remainders. A run sum is a difference of two prefixes; it is divisible by k when both prefixes share a remainder.
  4. 4Code the map. Seed remainder 0 at −1, keep only the first index, and check the length is at least 2.
  5. 5Test out loud. Run [1, 6] with k = 6, [5, 0, 0] and a single element before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?