![]() |
VOOZH | about |
Given a doubly linked list containing n nodes, each node is at most k-indices away from its target position. The problem is to sort the given doubly linked list. The distance can be assumed in either of the directions (left and right).
Examples:
Input: Doubly Linked List : 3 <-> 2 <-> 1 <-> 5 <-> 6 <-> 4 , k = 2
Output: 1 <-> 2 <-> 3 <-> 4 <-> 5 <-> 6Input: Doubly Linked List : 5 <-> 6 <-> 7 <-> 3 <-> 4 <-> 4 , k = 3
Output: 3 <-> 4 <-> 4 <-> 5 <-> 6 <-> 7
The idea is to use insertion sort to sort the doubly linked list. While inserting each element in the sorted part of the list, there will be atmost k swaps to place the element to its correct position since every node is is atmost k steps away from its correct position.
Below is the implementation of the above approach:
1 2 3 5
Time Complexity:O(n*k)
Auxiliary Space: O(1)
We can sort the list using the Min Heap data structure. The approach is same as discussed 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.
Below is the implementation of the above approach:
1 2 3 5
Time Complexity: O(n*log k)
Auxiliary Space: O(k)