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
19 changes: 19 additions & 0 deletions Problem1.cpp
Original file line number Diff line number Diff line change
@@ -1 +1,20 @@
// MISSING ELEMENT IN A SORTED ARRAY

int missingNumber(vector<int>& 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
}

48 changes: 48 additions & 0 deletions Problem2.cpp
Original file line number Diff line number Diff line change
@@ -1 +1,49 @@
//DESIGN A MIN HEAP

class minHeap{
vector<int> 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;
}
};