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.
Sort each list individually in MlogM and NlogN. Then merge two sorted lists.
Time complexity: O( MlogM + NlogN )
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<m then:
O(nlogn+ mlogm) = O(mlogm)
and
O(n+m)log(n+m)) = O(nlog(n+m) + mlog(n+m)) = O(nlog(m) + mlog(m)) = O(mlogm)
Symetrically, if m<n both are O(nlogn)
In fact, for n=m, approach 1 is the first step of merge sort
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With