Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Completed Competitive Coding-1 #1072

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions Problem1.java
Original file line number Diff line number Diff line change
@@ -1 +1,37 @@
class Problem1{
public static void main(String[] args){
Problem1 problem1 = new Problem1();
int[] arr = {1,2,3,4,6,7,8};
System.out.println("Missing element is: " + problem1.findMissingElement(arr));
}
private int findMissingElement(int[] nums){
if(nums == null || nums.length == 0){
return -1;
}
/*Logic: Perform binary search and match the current value with index.
* If index and value don't match search left else search right. */
int low = 0; int mid; int high = nums.length - 1;

// Edge cases resolution
if(nums[low] != 1) return 1;
else if (nums.length > 1 && nums[high] != high + 1 && nums[high - 1] == high){
return nums.length; // Could also return high + 1
}
// Begin binary search
while(low <= high) {
mid = low + (high - low) / 2;
// Missing element found
if(nums[mid] > (mid + 1) && nums[mid - 1] == mid){
return mid + 1;
}
else if(nums[mid] == mid + 1){
// Consistent till now so search right
low = mid + 1;
}
// Search left
else high = mid - 1;
}
// If there is no missing element
return -1;
}
}