Skip to content
Open
Show file tree
Hide file tree
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
17 changes: 17 additions & 0 deletions problem1.py
Original file line number Diff line number Diff line change
@@ -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<r:
m=l+(r-l)//2
# If it is true then until that point, numbers are in correct position, must be on right side
if arr[m] == m+1:
l=m+1
#must be on left side including middle
else:
r=m
return l+1

58 changes: 58 additions & 0 deletions problem2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
class MinHeap:
def __init__(self):
self.minheap = []

def getMin(self):
if not self.minheap:
return None
return self.minheap[0]

def insert(self, val):
self.minheap.append(val)
index = len(self.minheap) - 1

# heapify up
# Swapping parent and current element until it is less than parent
# As parent needs to be the smallest of all children
while index > 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