Skip to content

Commit b378f52

Browse files
committed
Updated explanation with necessary changes
1 parent c289acf commit b378f52

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

Arrays & Strings/Two Sum/Explanation.md

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,33 @@
11
Explanation (C solution):
22

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.
3+
## Two Sum II - Input Array is Sorted
4+
5+
### Difficulty : Easy
6+
### Category : Arrays, Two pointer
7+
8+
Leetcode Link : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
9+
10+
### Introduction
11+
12+
Two Sum II, a slightly modified version of Two Sum I where we get a sorted array and a target. We need to find two numbers in the array such that they add up to the target and return their indices in 1-based indexing.
13+
14+
### Intuition and Naive Approach/Brute Force
15+
16+
At first glance it seems simple. We could use two loops and check all the pairs and return the pair whose sum matches the target.
17+
18+
for(int i=0; i < n; i++) {
19+
for(int j=i+1; j < n; j++){
20+
if (num[i] + num[j] == target)
21+
return [i+1, j+1]
22+
}
23+
}
24+
25+
While this would give us the result it would totally negate any advantage we have with the array being sorted and furthermore it would result in a time complexity of O(n^2)
26+
27+
Space complexity: O(1)
28+
29+
### Optimized Solution
30+
The solution's optimized with the utilization of two pointers - at the start and end of the array respectively, let's say l and r.
531
We move inwards into the array until our start and end pointers don't cross over i.e left > right.
632
We check if the value at array[l] + array[r] (which is our sum) == target.
733

@@ -16,4 +42,18 @@ If Sum is equal to our target:
1642
-We've increased the index by 1 to facilitate 1-based indexing as given in the problem.
1743
-Return the malloced array.
1844

19-
Time Complexity: O(n)
45+
Time Complexity: O(n)
46+
Space complexity: O(1)
47+
48+
### Example
49+
Numbers = [2, 7, 11, 15], target = 9
50+
51+
The working :
52+
53+
l = 0, r = 3 → 2 + 15 = 17 → sum larger than target, reduce right pointer
54+
55+
l = 0, r = 2 → 2 + 11 = 13 → sum larger than target, reduce right pointer
56+
57+
l = 0, r = 1 → 2 + 7 = 9 → sum equal → return [1, 2]
58+
59+
Output: [1, 2]

0 commit comments

Comments
 (0)