AMAZON SDE FULL TIME PHONE SCREEN (ACCEPTED TO FINAL INTERVIEW)
Hey, i just had a phone screen interview with amazon for the SDE ROLE IN MEX and passed to the final interview, this was the asked question (i solved it with binary search and the formula n * (n+1)/2) for consecutive sums.
Question:
Given an interger N, return the integer number K in a way that the sum that goes from 1 to K-1 is equals to the sum that goes form k+1 to N (all inclusive), if there is no number that met the condition return -1.
Example.
Input.
N = 8
Output
K = 6
Explanation:
[1,2,3,4,5,6,7,8]
LEFT = SUM(1,K-1) = 1 + 2 + 3 + 4 +5 = 15
RIGHT = SUM(K+1,N) = 7 + 8 = 15
LEFT == RIGHT = TRUE
Code:
def Knumber(N):
left = 1
right = N
while left<=right:
m = (left+right)//2
lefts = (m*((m+1)/2))-m
rights = (N*((N+1)/2))-lefts-m
if rights==lefts:
return m
elif lefts<rights:
left=m+1
else:
right=m-1
return -1
runtime O(log N)
space O(1)


