Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two unsorted single linked list to one sorted single linked list

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?

like image 752
Green goblin Avatar asked Dec 06 '25 01:12

Green goblin


1 Answers

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

like image 145
amit Avatar answered Dec 08 '25 16:12

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!