20. Sort a K-Sorted Doubly Linked List

Problem Description

Given a doubly linked list where each node is at most k positions away from its correct place in the list, the task is to sort this list efficiently.

You are given a doubly linked list where the distance between a node and its target position is at most k. Sort the linked list in ascending order.

Example:

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

My Approach

  1. Priority Queue (Min-Heap)

    • The idea is to use a min-heap (priority queue) to keep track of the smallest element within the next k nodes. By popping the minimum element and adding the next element from the list, we ensure sorting within the k constraint.

  2. Steps:

    • Start by adding the first k+1 elements of the list to the min-heap.

    • Extract the minimum element from the heap to form the sorted list.

    • Continue adding the next elements from the unsorted list to the heap, maintaining k elements in the heap at a time.

    • Repeat this process until the entire list is sorted.

Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n*log k), where n is the number of nodes and k is the distance from the correct position. Inserting and extracting from the heap of size k takes O(log k) time, and we do this for all n nodes.

  • Expected Auxiliary Space Complexity: O(k), as we only maintain a heap of size k at any point.

Code (C++)

Code (Java)

Code (Python)

Contribution and Support

For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.

⭐ Star this repository if you find it helpful or intriguing! ⭐


📍Visitor Count

Last updated