AMAZON SDE FULL TIME PHONE SCREEN (ACCEPTED TO FINAL INTERVIEW)

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2024-06-07Added By Anonymous
Source: Link

Company: Amazon
Role: SDE
Interview Stage: Phone Screen
Location: Mexico
Year: unknown

Original Post Content:

Hey, I just had a phone screen interview with Amazon for the SDE role in Mexico 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 integer 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 from K+1 to N (all inclusive), if there is no number that meets 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)

Comments