-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathMissingElement.java
More file actions
22 lines (21 loc) · 883 Bytes
/
MissingElement.java
File metadata and controls
22 lines (21 loc) · 883 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
problem statement - Given a sorted array arr[] of n-1 integers, these integers are in the range of 1 to n. There are no duplicates in the array. One of the integers is missing in the array. Find the missing integer.
Approach: Using binary search, calculate the mid and check if the mid is in the right place if yes the missing number would be in the right side of mid update low = mid+1 position if not missing would be the left half
Time Complexity - O(log n)
Space Complexity - O(1)
*/
public class MissingElement {
public static int missingNumber(int[] arr) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == mid + 1) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return low + 1;
}
}