Time limit exceeded

the test cases are not passing because of the Time limit exceeded.

Hey
Can you post your code?

#include

using namespace std;

class node {

public:

int data;

node* next;

node(int data) {

this->data = data;

this->next = NULL;

}

};

void display(node* head) {

node* temp = head;

while (temp != NULL) {

    cout << temp->data <<" ";

    temp = temp->next;

}

}

void insertAtHead(node* &head, int data) {

node* n = new node(data);

n->next = head;

head = n;

}

void insertAtTail(node* &head, int data) {

if (head == NULL) {

    insertAtHead(head, data);

return;

}

node* temp = head;

while (temp->next != NULL) {

    temp = temp->next;

}

node* n = new node(data);

temp->next = n;

}

node* merge(node* a,node* b)

{

if(a==NULL)

{

return b;

}

if(b==NULL)

{

return a;

}

node* c;

if(a->data>=b->data)

{

    c=b;

    c->next=merge(a,b->next);

}

else

{

    c=a;

    c->next=merge(a->next,b);

}

return c;

}

int main() {

int t;

cin>>t;

node* head1=NULL;

node* head2=NULL;

for(int i=0;i<t;i++)

{

int n1;

    cin>>n1;

int a[n1];

for(int i=0;i<n1;i++)

{

        cin>>a[i];

        insertAtTail(head1,a[i]);

}

int n2;

    cin>>n2;

int b[n2];

for(int j=0;j<n2;j++)

{

        cin>>b[j];

        insertAtTail(head2,b[j]);

}

}

head1=merge(head1,head2);

display(head1);

return 0;

}

Your merge function seems fine.
Inside the main function-
Put the statements :-
node* head1=NULL;
node* head2=NULL;
inside the for loop, i. e. head1 and head2 have to be initialised for every test case.

Thank you! Now TLE is not coming but all the test cases are not passing.

1 Like

Hey
Can you tell me which cases are not working.

None of them are working. its compiling successful but on submission it didn’t pass any of the test case.

Hey is it working now or you need help?

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

its not working at all

can you pls help me with this?

hi @guptamuskan1305 please try this code https://ide.codingblocks.com/s/260665

There are 2 changes to be done, first, merge and print have to be done for every test case so they should be inside for loop.
Second answer for every test case should be in a new line so print a newline character at the end of print function.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.