Time Limit Exceeded . Someone please help!


#1

listnode* reverseBetween(listnode* A, int B, int C) {
printf("%d %d",B,C);
int min,max,diff,count=1;
if(B==C){
return A;
}else if(B<C){
printf("%d %d",min,max);
min=B;
max=C;
printf("%d %d",min,max);
}else{
min=C;
max=B;
}

printf("%d  %d",min,max);
diff=max-min;
listnode *minptr=A,*maxptr=A , *temp=NULL , *p;

while((diff>0)&&(maxptr!=NULL)){
    maxptr=maxptr->next;
    diff--;
}

if(maxptr==NULL){
    return A;
}

while((maxptr!=NULL)&&(count<min)){
   count++;
   maxptr=maxptr->next;
   temp=minptr;
   minptr=minptr->next;
}

if(maxptr==NULL){
    return A;
}


//now reversing
while(minptr!=maxptr){
    p=minptr->next;
    p->next=minptr;
    minptr=p;
}

minptr->next=maxptr->next;

if(temp==NULL){
    return maxptr;
}else{
    temp->next=maxptr;
    return A;
}

}


#2

My solution was also same :- If you notice the time complexity is O(n) + O (n). Ideally this is a time complexity of O(n) only but the time taken would be double. Try to think of a solution with a time complexity of O(n) that is one loop only instead of two O(n) loops. Hope it makes more sense