This straightforward approach involves checking all possible subarrays in the given array. We calculate the sum for each subarray and check if it equals k. Although simple, it can be inefficient for large arrays due to its O(n^2) time complexity.
Time Complexity: O(n^2)
Space Complexity: O(1)
1#include <iostream>
2#include <vector>
3
4int subarraySum(std::vector<int>& nums, int k) {
5 int count = 0;
6 for (size_t start = 0; start < nums.size(); ++start) {
7 int sum = 0;
8 for (size_t end = start; end < nums.size(); ++end) {
9 sum += nums[end];
10 if (sum == k) ++count;
11 }
12 }
13 return count;
14}
15
16int main() {
17 std::vector<int> nums = {1, 1, 1};
18 int k = 2;
19 std::cout << subarraySum(nums, k) << std::endl;
20 return 0;
21}
22
The C++ code functions similarly to the C code, using nested loops to check sums of all subarrays, incrementing the count whenever the sum equals k. This straightforward approach results in O(n^2) time complexity, with O(1) space complexity.
This optimized approach uses a hashmap to store prefix sums, facilitating the identification of subarrays with the desired sum in constant time. By keeping a count of prefix sums that have been seen, we can determine how many times a specific sum - k has appeared, suggesting that a subarray ending at the current position sums to k.
Time Complexity: O(n)
Space Complexity: O(n)
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int subarraySum(int* nums, int numsSize, int k) {
6 int count = 0, sum = 0, i;
7 int *prefixSumCount = calloc(20000, sizeof(int));
8 int offset = 10000;
9 prefixSumCount[offset] = 1;
10
11 for (i = 0; i < numsSize; i++) {
12 sum += nums[i];
13 int target = sum - k;
14 count += prefixSumCount[target + offset];
15 prefixSumCount[sum + offset]++;
16 }
17
18 free(prefixSumCount);
19 return count;
20}
21
22int main() {
23 int nums[] = {1, 1, 1};
24 int k = 2;
25 int size = sizeof(nums)/sizeof(nums[0]);
26 printf("%d\n", subarraySum(nums, size, k));
27 return 0;
28}
29
This C implementation uses a hash table to track the occurrence of prefix sums, adjusted with an offset for negative indices safety, enabling identification of subarrays summing to k. The time complexity reduces to O(n), with space complexity also improving due to the hash table.