




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.
1using System;
2using System.Collections.Generic;
3
4class Program {
5    public static bool CheckSubarraySum(int[] nums, int k) {
6        Dictionary<int, int> remainderMap = new Dictionary<int, int>();
7        remainderMap.Add(0, -1);
8        int sum = 0;
9        for (int i = 0; i < nums.Length; i++) {
10            sum += nums[i];
11            int mod = sum % k;
12            if (mod < 0) mod += k;
13            if (remainderMap.ContainsKey(mod)) {
14                if (i - remainderMap[mod] > 1) return true;
15            } else {
16                remainderMap[mod] = i;
17            }
18        }
19        return false;
20    }
21
22    static void Main() {
23        int[] nums = {23, 2, 4, 6, 7};
24        int k = 6;
25        Console.WriteLine(CheckSubarraySum(nums, k));
26    }
27}This C# solution uses a Dictionary to track the remainder of the cumulative sums divided by k, akin to a hashmap in other languages. The implementation seamlessly handles negative modulo results by incrementing with k.
The function checks for at least two consecutive indices having the same sum remainder and returns true for successful findings, returning false otherwise.
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.