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.
- Merge K sorted Doubly Linked List in Sorted Order
- Insert value in sorted way in a sorted doubly linked list
- Remove duplicates from a sorted doubly linked list
- Insertion Sort for Doubly Linked List
- Bubble Sort On Doubly Linked List
- Sort the biotonic doubly linked list
- Sort the biotonic doubly linked list | Set-2
- Merge Sort for Doubly Linked List
- Find pairs with given product in a sorted Doubly Linked List
- Count triplets in a sorted doubly linked list whose sum is equal to a given value x
- Sorted insert in a doubly linked list with head and tail pointers
- Count triplets in a sorted doubly linked list whose product is equal to a given value x
- Sort linked list which is already sorted on absolute values
- Sort a linked list that is sorted alternating ascending and descending orders?
- Sorted merge of two sorted doubly circular linked lists
- Difference between Singly linked list and Doubly linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Construct a Doubly linked linked list from 2D Matrix
- Reverse a Doubly Linked List | Set-2
Improved By : Akanksha_Rai