Given two unsorted single linked list of size M and N. The task is to create a single sorted linked list. No new nodes should be created.
I have thought of two approaches.
Approach 1:
Sort each list individually in MlogM and NlogN. Then merge two sorted lists.
Time complexity: O( MlogM + NlogN )
Approach 2:
Attach the second list to the end of first list. Then sort the list.
Time Complexity: O( (M + N) log(M + N) )
Which approach is better?
Is there still any better approach?
Asymptotically speaking – it is the same.
if
n<mthen:Symetrically, if
m<nboth areO(nlogn)In fact, for
n=m, approach 1 is the first step of merge sort