diff --git a/lib/twoSumHashTable/index.ts b/lib/twoSumHashTable/index.ts new file mode 100644 index 0000000..4828ed9 --- /dev/null +++ b/lib/twoSumHashTable/index.ts @@ -0,0 +1,3 @@ +import { twoSumHashTable } from "./twoSumHashTable"; + +export default twoSumHashTable; diff --git a/lib/twoSumHashTable/twoSumHashTable.test.ts b/lib/twoSumHashTable/twoSumHashTable.test.ts new file mode 100644 index 0000000..aad31e4 --- /dev/null +++ b/lib/twoSumHashTable/twoSumHashTable.test.ts @@ -0,0 +1,14 @@ +import { describe, it, expect } from "vitest"; +import { twoSumHashTable } from "./twoSumHashTable.ts"; + +describe("twoSumHashTable", () => { + let sortedArray = [-12, 1, 4, 6, 22]; + + it("twoSumHashTable", () => { + expect(twoSumHashTable(sortedArray, 4)).toBe(2); + }); + + it("twoSumHashTable", () => { + expect(twoSumHashTable(sortedArray, 3)).toBe(-1); + }); +}); diff --git a/lib/twoSumHashTable/twoSumHashTable.ts b/lib/twoSumHashTable/twoSumHashTable.ts new file mode 100644 index 0000000..3f85ef9 --- /dev/null +++ b/lib/twoSumHashTable/twoSumHashTable.ts @@ -0,0 +1,24 @@ +export function twoSumHashTable(nums: number[], target: number): number[] { + const result: number[] = []; + const hashTable: Record = {}; + let i = 0; + + + while (i < nums.length) { + let key = nums[i]; + let val = i; + let searchKey = String(target - key); + + if (searchKey in hashTable) { + result.push(hashTable[searchKey]); + result.push(val); + break; + } else { + hashTable[key] = val; + } + + i++ + } + + return result; +};