




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.
1#include <stdbool.h>
2#include <stdio.h>
3
4bool checkSubarraySum(int* nums, int numsSize, int k) {
5    int
In this C implementation, we use a dynamically allocated array to simulate a hashmap. We initialize all elements to -1, except the zero remainder, which is initialized to index 0 to handle the case where a subarray from the start has a sum that is a multiple of k.
The main loop updates the cumulative sum, calculates its modulo with k, and checks if this remainder was seen before in the hashmap, with the appropriate handling for negative mod cases. If so and the subarray has at least length 2, it returns true. Otherwise, it logs the index of this new remainder.
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.
#include <vector>
using namespace std;
bool checkSubarraySum(vector<int>& nums, int k) {
    for (int start = 0; start < nums.size() - 1; ++start) {
        int sum = nums[start];
        for (int end = start + 1; end < nums.size(); ++end) {
            sum += nums[end];
            if (sum % k == 0) return true;
        }
    }
    return false;
}
int main() {
    vector<int> nums = {23, 2, 4, 6, 7};
    int k = 6;
    cout << (checkSubarraySum(nums, k) ? "true" : "false") << endl;
    return 0;
}This C++ solution implements the brute force methodology, evaluating every feasible subarray using a nested loop to compute their sums and check for multiples of k. This approach effectively tests all possible combinations albeit slowly.