1228. Missing Number In Arithmetic Progression
Last updated
Last updated
/**
* Time complexity : O(n). Where n is the length of array arr since in
* the worst case we iterate over the entire array.
* Space complexity : O(1). Algorithm requires constant space to execute.
*/
class Solution {
public int missingNumber(int[] arr) {
int n = arr.length;
// Get the difference `difference`.
int difference = (arr[arr.length - 1] - arr[0]) / n;
// The expected element equals the starting element.
int expected = arr[0];
for (int val : arr) {
// Return the expected value that doesn't match val.
if (val != expected) return expected;
// Next element will be expected element + `difference`.
expected += difference;
}
return expected;
}
}/**
* Time complexity : O(logn).Where n is the length of array arr since
* we cut the search space in half at every iteration.
* Space complexity : O(1). Algorithm requires constant space to execute.
*/
class Solution {
public int missingNumber(int[] arr) {
int n = arr.length;
int diff = (arr[n-1]-arr[0]) / n;
if(diff == 0) {
return arr[0];
}
int low = 0, high = n-1;
while(low <= high) {
int mid = low + (high-low)/2;
if(arr[mid] == arr[0] + mid * diff) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return arr[0] + low * diff;
}
}