diff --git a/Problem1.cpp b/Problem1.cpp index 8b137891..cd6f167e 100644 --- a/Problem1.cpp +++ b/Problem1.cpp @@ -1 +1,20 @@ +// MISSING ELEMENT IN A SORTED ARRAY + +int missingNumber(vector& nums) { + int low = 0, high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (nums[mid] == mid + 1)// check if the index and the element are right or not for mid + // if mid is at the right position it means,left half of mid sorted and theres nothing missing + low = mid + 1;//hence we increment low by mid + 1 + else + high = mid - 1;// if mid index and mid element dont pass the if condition + } + + return low + 1;// after repetitive looping we will eventually come out of the loop when low>high + // in that case we can find the missing by returning low + 1 + // return "low" if you want the position where the element is supposed to be in +} diff --git a/Problem2.cpp b/Problem2.cpp index 8b137891..6b81d606 100644 --- a/Problem2.cpp +++ b/Problem2.cpp @@ -1 +1,49 @@ +//DESIGN A MIN HEAP + +class minHeap{ + vector h; + + public: + minHeap() {} + + int getMin(){ + return h[0]; + } + + void insert(int x){ + h.push_back(x); + int i = h.size() - 1; + + while(i > 0 && (i-1)/2 > i){ + swap(h[(i-1)/2],h[i]); + i = i - 1/2;//root + } + } + + int extractMin(){ + int minVal = h[0]; + h[0] = h.push_back(); + h.pop_back(); + + int i = 0; + int n = h.size(); + + while(true){ + int l = 2*i + 1;//left + int r = 2*i + 2;//right + int s = i; + + if (l < n && h[l] < h[s]) s = l;//left child exists + + if (r < n && h[r] < h[s]) s = r;//right child exists + + if (s == i) break;//parent is already smaller than both children + + swap(h[i], h[s]); + + i = s; + } + return minVal; + } +};