Given a doubly linked list containing n nodes, where each node is at most k away from its target position in the list. The problem is to sort the given doubly linked list.
For example, let us consider k is 2, a node at position 7 in the sorted doubly linked list, can be at positions 5, 6, 7, 8, 9 in the given doubly linked list.
Naive Approach: Sort the given doubly linked list using insertion sort technique.
Time Complexity: O(nk)
Auxiliary Space: O(1)
Efficient Approach: We can sort the list using the MIN HEAP data structure. The approach has been explained in Sort a nearly sorted (or K sorted) array. We only have to be careful while traversing the input doubly linked list and adjusting the required next and previous links in the final sorted list.
Original Doubly linked list: 3 6 2 12 56 8 Doubly linked list after sorting: 2 3 6 8 12 56
Time Complexity: O(nLogk)
Auxiliary Space: O(k)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Insert value in sorted way in a sorted doubly linked list
- Merge K sorted Doubly Linked List in Sorted Order
- Sorted merge of two sorted doubly circular linked lists
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Difference between Singly linked list and Doubly linked list
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Remove duplicates from a sorted doubly linked list
- Sorted insert in a doubly linked list with head and tail pointers
- Find pairs with given product in a sorted Doubly Linked List
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Merge Sort for Doubly Linked List
- Insertion Sort for Doubly Linked List
- Sort the biotonic doubly linked list
- Sort the biotonic doubly linked list | Set-2
- Bubble Sort On Doubly Linked List
- Construct a Doubly linked linked list from 2D Matrix
- Given a linked list which is sorted, how will you insert in sorted way
- Sort a linked list that is sorted alternating ascending and descending orders?
- Sort linked list which is already sorted on absolute values
Improved By : Akanksha_Rai