Skip to content

Instantly share code, notes, and snippets.

@loromits
Last active September 4, 2018 08:49
Show Gist options
  • Save loromits/170e14c42efe2d56e48e9766105797bb to your computer and use it in GitHub Desktop.
Save loromits/170e14c42efe2d56e48e9766105797bb to your computer and use it in GitHub Desktop.
3SUM problem raw algorithm with O(n²) at worst
extension Collection where Element: Comparable & Numeric {
typealias Triplet = (Element, Element, Element)
func threeSum() -> [Triplet] {
var result = [Triplet]()
let sortedSelf = sorted()
for (offset, a) in sortedSelf.dropLast().enumerated() {
var slice = sortedSelf.dropFirst(offset + 1)
while slice.count > 1, let b = slice.first, let c = slice.last {
if a + b + c == 0 {
result.append((a, b, c))
slice = slice.dropFirst().dropLast()
} else if a + b + c > 0 {
slice = slice.dropLast()
} else {
slice = slice.dropFirst()
}
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment