INPUT:
- Sorted array of positive, natural numbers,
EXPECTED COMPLEXITY:
- Time:
O(n) - Additional space:
O(1)
Example:
Input:
arr = {2,3,17,30}
x=10
Expected behavior:
The function prints the indexes : 1,2 and returns true since (3+17)/2 = x = 10
Input:
x = 30
Expected behavior:
The function will print the index 3
and return true since (30)/1 = x = 30`
My approach to the algorithm:
we will take the arithmatic mean starting with the first element in the array. If x is greater than our result we will add the next element in the array to the arithmatic mean.Else we will subtract the first element from the arithmatc mean.
I tried it and it didn't work. Can anyone help me?
If your k reaches array length, no solution. Else you have the solution. Complexity O(n) as if step 3 you only add one number as previous sum + ak+1 was greater than k*target and you can only move left border only n times.
Working properly for arrays with all numbers positive. Small modifications required for negatives but on interviews they often ask about arrays with all numbers positive. Some additional escape conditions might be needed in case there is no proper solution.