From 5f04776705a9b5096bf7e8f26ef8470b261a1211 Mon Sep 17 00:00:00 2001 From: "ravip1797@gmail.com" Date: Wed, 29 Jan 2025 02:06:33 -0600 Subject: [PATCH] Completed Missing Number --- .gitignore | 10 ++++++++++ MissingNumber.java | 42 ++++++++++++++++++++++++++++++++++++++++++ Problem1.java | 1 - 3 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 MissingNumber.java delete mode 100644 Problem1.java diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bea15a1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# Ignore VS Code settings +.vscode/ + +# Ignore compiled files +*.class +*.o + +# Ignore dependencies +node_modules/ +target/ diff --git a/MissingNumber.java b/MissingNumber.java new file mode 100644 index 00000000..4c097c8f --- /dev/null +++ b/MissingNumber.java @@ -0,0 +1,42 @@ +// Overall Time Complexity : O log(n) . The n is number of elements in the search space. +// Overall Space Complexity : O(1) . The space complexity of storing the values in variables like low, high uses constant space. +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No issues faced during implementation + + +// The solution to the problems involves identifying whether the missing element is on the right side or left of the sorted array. +// This is achieved by checking if nums[mid] matches mid + 1, then the missing number is on the right else its left. + +class MissingNumber { + private static int missing_number(int nums[]){ + int n = nums.length; + int low = 0; + int high = n-1; + + if (nums[0] != 1) // Case to handle if the first element is missing + return 1; + + if (nums[n - 1] != (n + 1)) // Case to handle if the last element is missing + return n + 1; + + while(low<=high){ + int mid = low+(high-low)/2; + + if(nums[mid]!=mid+1){ + high = mid -1; + } + else{ + low = mid +1; + } + + } + return low+1; + + + } + public static void main(String[] args) { + int []nums = {1,2,3,4,5,6,8}; + int res = missing_number(nums); + System.out.println("The missing number is "+res); + } +} diff --git a/Problem1.java b/Problem1.java deleted file mode 100644 index 8b137891..00000000 --- a/Problem1.java +++ /dev/null @@ -1 +0,0 @@ -