Skip to content

Commit d37a3a8

Browse files
committed
twoSum
1 parent df37585 commit d37a3a8

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

two-sum/sounmind.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function twoSum(nums: number[], target: number): number[] {
2+
// Pair each element with its index
3+
const numsWithIndex = nums.map((value, index) => ({ value, index }));
4+
5+
// Sort the array based on the values
6+
numsWithIndex.sort((a, b) => a.value - b.value);
7+
8+
let left = 0;
9+
let right = numsWithIndex.length - 1;
10+
11+
while (left < right) {
12+
const sum = numsWithIndex[left].value + numsWithIndex[right].value;
13+
14+
if (sum === target) {
15+
return [numsWithIndex[left].index, numsWithIndex[right].index];
16+
} else if (sum < target) {
17+
left++;
18+
} else {
19+
right--;
20+
}
21+
}
22+
23+
return []; // In case there is no solution
24+
}

0 commit comments

Comments
 (0)