Practice #2
Lesson 11 of 14 in Coddy's Hash Tables - Data Structures Series #4 course.
Challenge
EasyWrite a function twoSum that gets an integer array arr and an integer target, and returns the indices of the two elements whose values add up to target.
Return the indices in ascending order: [smaller_index, larger_index]. Each input has exactly one valid pair.
You must use the HashMap class provided in hashmap.<ext> — do not use language built-ins like sets, dicts, or maps.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line[8192];
char tline[64];
if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
if (!fgets(tline, sizeof(tline), stdin)) tline[0] = '\0';
int arr[4096];
int n = 0;
char* tok = strtok(line, " \t\r\n");
while (tok) { arr[n++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int target = atoi(tline);
int rs = 0;
int* r = twoSum(arr, n, target, &rs);
printf("%d %d\n", r[0], r[1]);
return 0;
}