#include <stdio.h>
#include <stdlib.h>
// Node for hashmap chaining
typedef struct Node {
int key;
int value;
struct Node* next;
} Node;
// Simple hashmap with chaining
#define HASH_SIZE 1000
Node* hashMap[HASH_SIZE];
unsigned int hash(int key) {
return (unsigned int)((key % HASH_SIZE + HASH_SIZE) % HASH_SIZE);
}
// Find node with key
Node* findNode(int key) {
unsigned int h = hash(key);
Node* curr = hashMap[h];
while (curr) {
if (curr->key == key) return curr;
curr = curr->next;
}
return NULL;
}
// Insert or update key with value
void put(int key, int value) {
Node* node = findNode(key);
if (node) {
node->value += value; // increment count
} else {
unsigned int h = hash(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = hashMap[h];
hashMap[h] = newNode;
}
}
// Get value for key or 0 if not found
int get(int key) {
Node* node = findNode(key);
if (node) return node->value;
return 0;
}
int subarraySum(int* nums, int numsSize, int k) {
int count = 0;
int prefix_sum = 0;
// Initialize hashmap
for (int i = 0; i < HASH_SIZE; i++) hashMap[i] = NULL;
put(0, 1); // prefix sum 0 occurs once
for (int i = 0; i < numsSize; i++) {
prefix_sum += nums[i]; // add current element to prefix sum
count += get(prefix_sum - k); // check if prefix_sum-k seen before
put(prefix_sum, 1); // add/update prefix_sum count
}
return count;
}
int main() {
int nums[] = {1, 2, 3};
int k = 3;
int result = subarraySum(nums, 3, k);
printf("%d\n", result);
return 0;
}put(0, 1); // prefix sum 0 occurs once
initialize map with sum zero to count subarrays starting at index 0
prefix_sum += nums[i]; // add current element to prefix sum
update running sum including current element
count += get(prefix_sum - k); // check if prefix_sum-k seen before
add count of previous prefix sums that allow subarray sum k ending here
put(prefix_sum, 1); // add/update prefix_sum count
record current prefix sum in map for future subarrays