diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..79986c81 --- /dev/null +++ b/problem1.py @@ -0,0 +1,17 @@ +#Find Missing Number in a sorted array +# Provide an array of n-1 integers in the range of 1 to n with no duplicates in list, +# One of the integers is missing in the list. Write a code to find the missing integer. +def search(arr): + l=0 + r=len(arr)-1 + # Trying to make the binary search stop when both and l are equal + while l 0: + parent = (index - 1) // 2 + if self.minheap[index] < self.minheap[parent]: + self.minheap[index], self.minheap[parent] = self.minheap[parent], self.minheap[index] + index = parent + else: + break + + def extractMin(self): + # If there are no elements return None + if not self.minheap: + return None + + # since the root is always the minimum value swap the root with the last value + # remove the min value and store it to return later after we correct the heap + self.minheap[0], self.minheap[-1] = self.minheap[-1], self.minheap[0] + min_val = self.minheap.pop() + + index = 0 + n = len(self.minheap) + + + # B/w the parent and its children find out which is the smallest and swap + + while True: + l = 2*index + 1 + r = 2*index + 2 + smallest = index + + if l < n and self.minheap[l] < self.minheap[smallest]: + smallest = l + if r < n and self.minheap[r] < self.minheap[smallest]: + smallest = r + # If the parent is already the smallest among the children heap property is already satisfied + if smallest == index: + break + # If not, swap the parent with the minimum of the 2 children + self.minheap[index], self.minheap[smallest] = self.minheap[smallest], self.minheap[index] + index = smallest + + return min_val +