Skip to content

Instantly share code, notes, and snippets.

@avanishgiri
Last active December 24, 2015 13:39
Show Gist options
  • Save avanishgiri/6806773 to your computer and use it in GitHub Desktop.
Save avanishgiri/6806773 to your computer and use it in GitHub Desktop.
Solution to find pivot in linear time
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