Given an integer array
A good subarray is a subarray where:
- its length is at least two, and
-
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 ofk if there exists an integern such thatx = n * k .0 is always a multiple ofk .
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
Output: false
Explanation: There is no contiguous subarray that adds upto 13 or multiples of 13.
Constraints:
1 < nums.length <= 105 0 <= nums[i] <= 109 0 <= sum(nums[i]) <= 231 - 1 1 <= k <= 231 - 1
Contents
Solution 1 - Create prefix sum array and then find if there is a possible continuous subarray with K multiples
In this approach, we will first compute a
-
Loop through prefix sum array, and divide the prefix sum with
k and store theremainder and current indexindex into aHashMap . The reason why we are storing indexes is to check minimum array length when we find a subarray with multiple ofk , the subarray length should be atleast 2. -
When you put
remainder intoHashMap , check if it already exists, that means current prefix is a multiple ofk .
For example if the input array is[23, 4, 2] andk=6 , then prefix sum array will be[23, 27, 29] - If we divide 23 with 6, we get remainder as 5 for index 0.
- For index 1, we get remainder as 3.
- For index 2, we get remainder as 5, but there is already a remainder 5 at index 0, so this means that the cumulative sum after index 0, is a multiple of 6 (which is 4, 2).
-
If the
remainder not exists, then we simply add it to theHashMap with its index as value. -
There are two edge cases:
-
First number in the input array is multiple of
k , for example[24,....] and k =6, we will get remainder as0 , but the array length at this index is 1. -
0 is also a multiple of
k , so there may be scenario which has 0's in the input array, for example[0, 0, 2] . Checking for
HashMap with0 as key and-1 as value. So that when we check indexes differences it wont match minimum length of 2. -
First number in the input array is multiple of
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n), since we are creating prefix sum array with size
Above implementations source code can be found at