Skip to content

Commit c289acf

Browse files
committed
Commit #123 - Added Two Sum II solution and explanation in C - 07.04.2025
1 parent 3554883 commit c289acf

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Explanation (C solution):
2+
3+
Two Sum II, a slightly modified version of Two Sum I where we get a sorted array.
4+
The solution's straightforward with the utilization of two pointers - at the start and end of the array respectively, let's say l and r.
5+
We move inwards into the array until our start and end pointers don't cross over i.e left > right.
6+
We check if the value at array[l] + array[r] (which is our sum) == target.
7+
8+
Since it's a sorted array. If:
9+
1. Sum is greater than Target
10+
-Then we know we need a smaller value to match or get close to the target, hence we decrease the end pointer , pointing to a smaller value (second largest value and so on..).
11+
2. Sum is lesser than Target
12+
-Then we need a larger value to match or get close to the target, hence we increase the start pointer, pointing to a larger value(second smallest value and so on..).
13+
14+
If Sum is equal to our target:
15+
-Store the indexes of the two values in the malloced array (dynamic array since we can't directly return two values from a function in C)
16+
-We've increased the index by 1 to facilitate 1-based indexing as given in the problem.
17+
-Return the malloced array.
18+
19+
Time Complexity: O(n)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
3+
int l = 0;
4+
int r = numbersSize-1;
5+
6+
int* answer = (int*)malloc(2*sizeof(int)); //dynamic memory allocation
7+
*returnSize = 2; //we're returning two values
8+
9+
while (l < r)
10+
{
11+
int sum = (numbers[l] + numbers[r]);
12+
if (sum == target)
13+
{
14+
answer[0] = l+1; //facilitating 1-based indexing as required by the problem.
15+
answer[1] = r+1;
16+
return answer;
17+
}
18+
else if (sum > target)
19+
{
20+
r--; //point to a smaller value to reduce the sum
21+
}
22+
else
23+
{
24+
l++; //point to a larger value to increase the sum
25+
}
26+
27+
}
28+
return 0;
29+
30+
}

0 commit comments

Comments
 (0)