




Sponsored
Sponsored
The idea is to use a running or cumulative sum and check the remainder when this sum is divided by k. If any two prefix sums have the same remainder, the subarray sum between these indices is divisible by k.
We maintain a hashmap to store each remainder and its index. As we iterate over the array, we update the running sum and check its remainder. If the remainder has been seen before and the subarray length is at least 2, we return true. If not, we continue. If we finish the loop without finding such a subarray, we return false.
Time Complexity: O(n), where n is the length of nums, since we iterate over the array only once.
Space Complexity: O(k), as we use a hashmap (or array) to store remainders which can be 0 through k-1 in the worst case.
1def check_subarray_sum(nums, k):
2    rem_map = {0: -1}
3    total = 0
4    for i, num in enumerate(nums):
5        total += num
6        remainder = total % k
7        if remainder < 0:
8            remainder += k
9        if remainder in rem_map:
10            if i - rem_map[remainder] > 1:
11                return True
12        else:
13            rem_map[remainder] = i
14    return False
15
16if __name__ == '__main__':
17    nums = [23, 2, 4, 6, 7]
18    k = 6
19    print(check_subarray_sum(nums, k))This Python function operates using a dictionary that maps remainders of the sum modulo k to their indices, allowing detection of the necessary subarray efficiently. The key structure of the solution lies in the comparison of indices whenever a remainder recurs.
The function captures and accounts for negative remainder values and adjusts back into the valid range with k, ensuring accuracy in diverse numeric scenarios.
This approach attempts every possible subarray of length at least 2, calculating the sum for each and checking if it is a multiple of k. Although not efficient, this serves as a basic solution for smaller inputs.
The process involves iterating over each possible starting point of a subarray, then for each starting point, iterating over each possible ending point to compute the sum, subsequently verifying its divisibility by k.
Time Complexity: O(n²) because of the nested loop structure iterating through potential subarray limits.
Space Complexity: O(1) as no extra space apart from a few variables is used.
This brute force approach implemented in C checks all subarrays of length at least 2. It attempts every start position and iterates all feasible end positions to compute subarray sum and verify divisibility by k.