VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-k-sorted-doubly-linked-list/

⇱ Sort a nearly sorted doubly linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort a nearly sorted doubly linked list

Last Updated : 31 Aug, 2024

Given a doubly linked list containing 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 <-> 6

Input: Doubly Linked List : 5 <-> 6 <-> 7 <-> 3 <-> 4 <-> 4 , k = 3
Output: 3 <-> 4 <-> 4 <-> 5 <-> 6 <-> 7

[Naive Approach] Using Insertion sort - O(n*k) time and O(1) space

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:


Output
1 2 3 5 

Time Complexity:O(n*k)
Auxiliary Space: O(1)

[Expected Approach] Using Min Heap - O(nlogk) time and O(k) space

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:


Output
1 2 3 5 

Time Complexity: O(n*log k)
Auxiliary Space: O(k)

Comment