Continuous Subarray Sum

Given an integer array nums and an integer k, return true if nums has a good subarray, and false otherwise. A good subarray has length at least two and its sum is a multiple of k. A subarray is a contiguous part of the array, and 0 counts as a multiple of every k.

30:00

Continuous Subarray Sum
medium
Free written solution
Topics
Companies

Given an integer array nums and an integer k, return true if nums has a good subarray, and false otherwise. A good subarray has length at least two and its sum is a multiple of k. A subarray is a contiguous part of the array, and 0 counts as a multiple of every k.

Example 1:
Input: {"nums":[23,2,4,6,7],"k":6}
Output: true
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 0≤nums[i]≤1090 \leq \text{nums}[i] \leq 10^9

  • 0≤∑nums[i]≤231−10 \leq \sum \text{nums}[i] \leq 2^{31} - 1

  • 1≤k≤231−11 \leq k \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[23,2,4,6,7],"k":6}

Seed the map with remainder 0 at index -1: the empty prefix has sum 0, so a prefix that is itself a multiple of 6 can match it.

nums, with prefix sum mod 6 under each index

∅

-1

0
23

0

.
2

1

.
4

2

.
6

3

.
7

4

.

remainder clock (mod 6)

0@-112345

first index of each remainder

0 → -1
Variables
VariableValue
k6
total0
first[0]-1
DepthFunction Call
Stack empty
0/7