From 8e904f4b14734d5c5376d17e056e0fdb9550d3f5 Mon Sep 17 00:00:00 2001 From: Vaishnavi Gawale Date: Sun, 4 Jan 2026 09:54:16 -0500 Subject: [PATCH] Done Competitive-Coding-1 --- find_missing_number.py | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 find_missing_number.py diff --git a/find_missing_number.py b/find_missing_number.py new file mode 100644 index 00000000..7ec2e777 --- /dev/null +++ b/find_missing_number.py @@ -0,0 +1,57 @@ +#-------------Solution 1------------- +def find_missing_number_formula(arr, n): + """ + arr: sorted list of n-1 integers from 1 to n + n: the upper bound of the range + Return the missing integer + + Approach : Taking the difference of Sum of Total array, and Sum of given array. + Time Complexity : O(n) + Space Complexity : O(1) + + """ + # Formula to get the sum of all integers from 1 to n + total_sum = n * (n + 1) // 2 + arr_sum = sum (arr) + missing_no = total_sum - arr_sum + return missing_no + +#-------------Solution 2------------- +def find_missing_number_binary(arr, n): + """ + arr: sorted list of n-1 integers from 1 to n + n: the upper bound of the range + Return the missing integer + + Approach : In sorted array, the difference of index and the element would be exactly 1, + If any no is missing the diff of next element would be 2. + + TIme Complexity : O(log n) + Space Complexity : O(1) + """ + l , r = 0 , n-2 + while l <= r: + mid = (l + r) // 2 + print(l, r, mid) + diff = arr[mid] - mid + if diff == 1: + l = mid + 1 + else: + r = mid - 1 + print("mid:",mid) + return arr[r] + 1 + + +def main(): + # Read input + # Example input: + # 1 2 3 4 6 7 8 + arr = list(map(int, input("Enter the array elements separated by space: ").split())) + # Since one number is missing, n = len(arr) + 1 + n = len(arr) + 1 + # Call the function + missing = find_missing_number_binary(arr, n) + # Print result + print("Missing number:", missing) +if __name__ == "__main__": + main()