Last active
December 24, 2015 13:39
-
-
Save avanishgiri/6806773 to your computer and use it in GitHub Desktop.
Solution to find pivot in linear time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def find_pivot(array) | |
return -1 if array.empty? | |
left = 0 | |
right = array[1..-1].inject(0,:+) | |
for i in 0...array.length | |
return i if left == right | |
left += array[i] | |
right -= array[i+1] || 0 | |
end | |
return -1 | |
end | |
p find_pivot([]) == -1 | |
p find_pivot([1]) == 0 | |
p find_pivot([1,1]) == -1 | |
p find_pivot([1,2,1]) == 1 | |
p find_pivot([1,-1,5,4,6,-2,1]) == 3 | |
p find_pivot([0,0]) == 0 | |
p find_pivot([1,0,0,1]) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment