You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Arrays & Strings/Two Sum/Explanation.md
+43-3Lines changed: 43 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,33 @@
1
1
Explanation (C solution):
2
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.
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.
5
31
We move inwards into the array until our start and end pointers don't cross over i.e left > right.
6
32
We check if the value at array[l] + array[r] (which is our sum) == target.
7
33
@@ -16,4 +42,18 @@ If Sum is equal to our target:
16
42
-We've increased the index by 1 to facilitate 1-based indexing as given in the problem.
17
43
-Return the malloced array.
18
44
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]
0 commit comments