Skip to content

Instantly share code, notes, and snippets.

@t0rn
Last active September 24, 2018 13:02
Show Gist options
  • Save t0rn/df6a52886c2415b703ae8e22fd40bc95 to your computer and use it in GitHub Desktop.
Save t0rn/df6a52886c2415b703ae8e22fd40bc95 to your computer and use it in GitHub Desktop.
extension Array where Element == Int {
var equilibriumIndexes: [Element]? {
var idxs = [Element]()
var sum = reduce(0,+)
var leftSum = 0
let count = self.count
for i in 0..<count {
sum = sum - self[i]
if leftSum == sum {
idxs.append(i)
}
leftSum = leftSum + self[i]
}
return idxs.isEmpty ? nil : idxs
}
}
[-3,2,-2,1,-2].equilibriumIndexes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment