Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Arrays & Strings/Two Sum/Explanation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Explanation (C solution):

Two Sum II, a slightly modified version of Two Sum I where we get a sorted array.
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.
We move inwards into the array until our start and end pointers don't cross over i.e left > right.
We check if the value at array[l] + array[r] (which is our sum) == target.

Since it's a sorted array. If:
1. Sum is greater than Target
-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..).
2. Sum is lesser than Target
-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..).

If Sum is equal to our target:
-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)
-We've increased the index by 1 to facilitate 1-based indexing as given in the problem.
-Return the malloced array.

Time Complexity: O(n)
30 changes: 30 additions & 0 deletions Arrays & Strings/Two Sum/Two Sum 2.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@

int* twoSum(int* numbers, int numbersSize, int target, int* returnSize) {
int l = 0;
int r = numbersSize-1;

int* answer = (int*)malloc(2*sizeof(int)); //dynamic memory allocation
*returnSize = 2; //we're returning two values

while (l < r)
{
int sum = (numbers[l] + numbers[r]);
if (sum == target)
{
answer[0] = l+1; //facilitating 1-based indexing as required by the problem.
answer[1] = r+1;
return answer;
}
else if (sum > target)
{
r--; //point to a smaller value to reduce the sum
}
else
{
l++; //point to a larger value to increase the sum
}

}
return 0;

}