Continuous Subarray Sum
Master this topic with zero to advance depth.
Continuous Subarray Sum
Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise.
Visual Representation
nums = [23, 2, 4, 6, 7], k = 6
Prefix Sum Modulo k:
- 23 % 6 = 5
- (23+2) % 6 = 25 % 6 = 1
- (25+4) % 6 = 29 % 6 = 5 (FOUND EXISTING REMAINDER!)
Subarray from index 1 to 2 has sum (2+4)=6 (multiple of 6).
Size = 2 (Valid)Examples
Level I: Brute Force (All Subarrays)
Intuition
Iterate through all possible subarrays and calculate their sum. If any sum is a multiple of k and length is , return true.
Detailed Dry Run
i=0, j=1: sum=23+2=25 (Not multiple of 6) i=1, j=2: sum=2+4=6 (Multiple of 6!) return true
Level II: Better Solution (Prefix Sum O(N²))
Intuition
Use a prefix sum array to calculate the sum of any subarray in O(1). Iterate through all pairs with and check if .
Detailed Dry Run
nums=[23, 2, 4], prefix=[0, 23, 25, 29] i=0, j=1: (25-0)%6 = 1 i=1, j=2: (29-23)%6 = 0 (Match!)
Level III: Prefix Sum + Modulo Hashing
Intuition
If the remainder of is the same as , then the subarray sum from to is a multiple of . We use a HashMap to store remainder -> first_seen_index and check if current_index - first_seen_index >= 2.
Detailed Dry Run
nums=[23, 2, 4], k=6. Map: {0: -1}
- rem=5. Map: {0:-1, 5:0}
- rem=(5+2)%6=1. Map: {0:-1, 5:0, 1:1}
- rem=(1+4)%6=5. Key 5 exists at idx 0. Diff 2-0=2. return true.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.