52. Linked-List-4: (Two singly LL problems)
- Add 2 LL✅🔥
- Poi of 2 LL✅
- merge 2 sorted LL✅
- merge K sorted LL✅
- sort LL🔥
Brute force-
traverse one LL and hash the nodes & when u traverse the other LL, the first visited node u visit is ans
--------------------------------------------------
Better-
instead of using extra space, we will move ptr of Longer LL till it reaches starting posn of shorter LL, and then we start simultaneous traversal of both
---------------------------------------------------
Optimal-
1. move both ptrs starting from respective heads
2. whenver a ptr reaches last node, move that ptr to head of other linked list & move other ptr as usual
3. now keep moving the ptrs & if u see step 2 situation then do above stuff & repeat
aise karte karte at one time, both ptrs will be vertically aligned, so then they would simultaneously reach common poi
Brute - store all elements and then sort them and convert this array into a LL
Optimal- (time: O(n1+n2) )
use 2 pointers across 2 LL conditionally and add smaller element to LL
instead of creating a new LL, just use one dummy node & start connection
---------------------------------------------------------------------------------------------------------------------------
Brute-
use array & sort array & then convert array to a new LL
Better- (time ~ N*k*k)
we will do a repeated merge 2 sorted LL, like first merge list 1 & 2 and then merge this new list with list 3 & so on
Optimal-(time- N*K*logK)
use min-heap
1. store all heads in a priority queue in form of pairs as ( val, node)
2. create a dummy node
3. add min out of pq to dummy->next and add pop wale node ka next into pq
4. repeat step 3
----------------------------------------------------------------------------------------------------------------------------
Brute- O(n) space
simple, store all elements in a data structure--> sort them-->over write the LL
1. divide the list into 2 lists and repeat the process till, we get single nodes
2. now sort them and merge using merge 2 sorted LL algo
3. repeat
1. find middle using tortoise hare algo
2. left LL start from head & right LL start from middle-->next
3. separate the 2 LL and call merge sort again recursively for these 2 LL to get 2 sorted LL
4. merge these 2 sorted LL
Tortoise hair algo returns second middle in case of even length LL, we want first middle in even length LL for split, so modify that algo
so we will start fast from (head--->next) instead of head
--------------------------------------------------------------------------------------------------------------
Comments
Post a Comment