Skip to content

Commit 1fc26da

Browse files
authored
Added solution to 3Sum
1 parent 0bf83f1 commit 1fc26da

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

3Sum and 4Sum/README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,53 @@ extension BidirectionalCollection where Element: Equatable {
7070
}
7171
```
7272

73+
### Assembling the Subsets
74+
75+
You'll keep track of 3 indices to represent the 3 numbers. The sum at any given moment is `array[l] + array[m] + array[r]`:
76+
77+
```
78+
m -> <- r
79+
[-4, -1, -1, 0, 1, 2]
80+
 l
81+
```
82+
83+
The premise is quite straightforward (given that you're familiar with 2Sum). You'll iterate `l` through the array. For every iteration, you also apply the 2Sum algorithm to elements after `l`. You'll check the sum every time you moving the indices to check if you found match. Here's the algorithm:
84+
85+
```
86+
func threeSum<T: BidirectionalCollection>(_ collection: T, target: T.Element) -> [[T.Element]] where T.Element: BinaryInteger & Comparable {
87+
let sorted = collection.sorted()
88+
var ret: [[T.Element]] = []
89+
90+
for l in sequence(first: sorted.startIndex, next: sorted.uniqueIndex(after:)) {
91+
var m = sorted.index(after: l)
92+
var r = sorted.index(before: sorted.endIndex)
93+
94+
while m < r {
95+
let sum = sorted[l] + sorted[m] + sorted[r]
96+
switch target {
97+
case sum:
98+
ret.append([sorted[l], sorted[m], sorted[r]])
99+
guard let nextMid = sorted.uniqueIndex(after: m), let nextRight = sorted.uniqueIndex(before: r) else { break }
100+
m = nextMid
101+
r = nextRight
102+
case ..<target:
103+
guard let nextMid = sorted.uniqueIndex(after: m) else { break }
104+
m = nextMid
105+
case target...:
106+
guard let nextRight = sorted.uniqueIndex(before: r) else { break }
107+
r = nextRight
108+
default: fatalError("Swift isn't smart enough to detect that this switch statement is exhausive")
109+
}
110+
}
111+
}
112+
113+
return ret
114+
}
115+
```
116+
117+
118+
119+
73120
## 4Sum
74121
Given an array S of n integers, find all subsets of the array with 4 values where the 4 values sum up to a target number.
75122

0 commit comments

Comments
 (0)