I thought of using linked list to do this problem. Why am I getting this sigtstp error? Here is link for my code.

In add() function, you are adding elements to the end of linked list,

for adding 1st element it take you 0 iteration to traverse to end of linked list,

for adding 2nd element it take you 1 iteration to traverse to end of linked list,

for adding 3rd element it take you 2 iterations to traverse to end of linked list,

so on…

i.e a total of 1+2+3+…+n-1 iterations.

This costs you **O(n*n) iterations** in total, which results in **TLE** verdict.

**=> How to reduce the iterations?**

**Solution :** Modify your add() function to add elements at the start of linked list,

i.e. the newest element you would add in the linked list will become your linked list’s current head.

This would help you reduce the element addition complexity from O(n*n) to **O(n)**.

1 Like