## Minheap: TLE

**Minheap: TLE**

The following is my code for MinHeap. But it is showing TLE for some input. Can someone please help me figure out where?

#include <cmath>

#include <cstdio>

#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

void swap(int *a,int *b){

int temp=*a;

*a=*b;

*b=temp;

return;

}

void heapify(vector<int> &heap,int index)

{

int length=heap.size();

int min=index;

int left=(index<<1)+1;

int right=(index<<1)+2;

if(left<length&&heap[left]<heap[min])

min=left;

if(right<length&&heap[right]<heap[min])

min=right;

if(min!=index)

{

swap(&heap[index],&heap[min]);

heapify(heap,min);

}

}

int main() {

int t,n;

string op;

scanf("%d",&t);

vector<int> heap;

while(t--) {

cin>>op;

//cout<<"Currently analysing"<<op<<"\n";

if(op=="insert") {

scanf("%d",&n);

heap.push_back(n);

int i=heap.size()-1;

while (i!=0&&heap[(i-1)>>1]>heap[i])

{

swap(&heap[i], &heap[(i-1)>>1]);

i =(i-1)/2;

}

}

else if(op=="getMin") {

if(heap.size()>0)

printf("%d\n",heap[0]);

else

printf("Empty\n");

/*for(int i=0;i<heap.size();i++)

cout<<heap[i]<<" ";

cout<<"\n";*/

}

else {

if(heap.size()>0)

{

heap.erase(heap.begin());

heapify(heap,0);

}

}

}

return 0;

}

**CareerCup**is the world's biggest and best source for software engineering interview preparation. See all our resources.

Open Chat in New Window