#include <stdio.h>
#include <stdlib.h>
// Simple hash node for storing number and index
typedef struct HashNode {
int key;
int val;
struct HashNode* next;
} HashNode;
// Hash map with chaining
#define HASH_SIZE 100
HashNode* hashMap[HASH_SIZE];
int hash(int key) {
return abs(key) % HASH_SIZE;
}
void insert(int key, int val) {
int h = hash(key);
HashNode* node = (HashNode*)malloc(sizeof(HashNode));
node->key = key;
node->val = val;
node->next = hashMap[h];
hashMap[h] = node;
}
int find(int key) {
int h = hash(key);
HashNode* curr = hashMap[h];
while (curr != NULL) {
if (curr->key == key) return curr->val;
curr = curr->next;
}
return -1;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
for (int i = 0; i < HASH_SIZE; i++) hashMap[i] = NULL;
for (int i = 0; i < numsSize; i++) {
int complement = target - nums[i];
int foundIndex = find(complement);
if (foundIndex != -1) {
int* result = (int*)malloc(2 * sizeof(int));
result[0] = foundIndex;
result[1] = i;
*returnSize = 2;
return result;
}
insert(nums[i], i);
}
*returnSize = 0;
return NULL;
}
int main() {
int nums[] = {2, 7, 11, 15};
int target = 9;
int returnSize = 0;
int* result = twoSum(nums, 4, target, &returnSize);
if (result != NULL) {
printf("[%d, %d]\n", result[0], result[1]);
free(result);
} else {
printf("No solution\n");
}
return 0;
}for (int i = 0; i < numsSize; i++) {
iterate over each number in the array
int complement = target - nums[i];
calculate the number needed to reach target
int foundIndex = find(complement);
check if complement is already in hash
if complement found, return indices
store current number and its index in hash