Sort a “k”sorted Doubly Linked list

Pattern: Doubly and circular lists

medium

Every node is at most k places from where it belongs, so the smallest remaining node is always among the next k + 1. Keep those k + 1 nodes in a min-heap, pop the smallest onto the output, and push the next node in.

The problem

Given the head of a doubly linked list where every node is at most k positions away from its place in sorted order, sort the list and return the head. For example, 3 ⇄ 6 ⇄ 2 ⇄ 12 ⇄ 56 ⇄ 8 with k = 2 becomes 2 ⇄ 3 ⇄ 6 ⇄ 8 ⇄ 12 ⇄ 56.

The link above is a GeeksforGeeks article. The function name sortAKSortedDLL is this guide's own. In this guide's code the node type is DNode, and the tests check every prev link.

Think first

  • Where can the smallest value of the whole list be?
  • After it is placed, where can the next smallest be?
  • Which data structure gives the smallest of a few items quickly?

Hints

    Brute force, and why it fails

    Insertion sort on the list is O(n × k) here, since each node moves at most k places. Merge sort ignores k and is O(n log n). A heap of size k + 1 gives O(n log k).

    The key insight

    "Nearly sorted" bounds how far ahead the next answer can hide. A heap that only holds that window turns sorting into a stream of small heap operations.

    Dry run

    30 
    61 
    22 
    123 
    564 
    85 
    heap2 3 6

    The list is 3 ⇄ 6 ⇄ 2 ⇄ 12 ⇄ 56 ⇄ 8 and k = 2. Put the first k + 1 = 3 nodes in a min-heap.

    Step 1 of 4

    The plan

    heap = min-heap of the first k + 1 nodes, by value
    newHead = null, tail = null, cur = node after them
    while heap is not empty:
        m = pop smallest
        link m after tail (m.prev = tail, tail.next = m), or make it newHead
        tail = m
        if cur is not null: push cur; cur = cur.next
    tail.next = null
    return newHead
    

    Complexity

    Time
    O(n log k)
    Space
    O(k)

    Each node is pushed and popped once on a heap of at most k + 1 nodes.

    Edge cases

    • k = 0: already sorted.
    • k at least the length: a full heap sort.
    • Equal values: any order among them is sorted.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public DNode sortAKSortedDLL(DNode head, int k) {
            if (head == null) return null;
            PriorityQueue<DNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
            DNode cur = head;
            for (int i = 0; i <= k && cur != null; i++) { heap.add(cur); cur = cur.next; }   // the first k + 1 nodes
            DNode newHead = null, tail = null;
            while (!heap.isEmpty()) {
                DNode min = heap.poll();            // the smallest of the next k + 1 must come next
                if (newHead == null) { newHead = min; min.prev = null; }
                else { tail.next = min; min.prev = tail; }
                tail = min;
                if (cur != null) { heap.add(cur); cur = cur.next; }
            }
            tail.next = null;
            return newHead;
        }
    }

    C++

    class Solution {
    public:
        DNode* sortAKSortedDLL(DNode* head, int k) {
            if (head == NULL) return NULL;
            auto cmp = [](DNode* a, DNode* b) { return a->val > b->val; };
            priority_queue<DNode*, vector<DNode*>, decltype(cmp)> heap(cmp);   // smallest value on top
            DNode* cur = head;
            for (int i = 0; i <= k && cur != NULL; i++) { heap.push(cur); cur = cur->next; }   // first k + 1 nodes
            DNode *newHead = NULL, *tail = NULL;
            while (!heap.empty()) {
                DNode* mn = heap.top();             // the smallest of the next k + 1 must come next
                heap.pop();
                if (newHead == NULL) { newHead = mn; mn->prev = NULL; }
                else { tail->next = mn; mn->prev = tail; }
                tail = mn;
                if (cur != NULL) { heap.push(cur); cur = cur->next; }
            }
            tail->next = NULL;
            return newHead;
        }
    };

    Python

    import heapq
    
    from lib import DNode
    
    class Solution:
        def sortAKSortedDLL(self, head: DNode, k: int) -> DNode:
            if head is None:
                return None
            heap, cur, order = [], head, 0          # order breaks ties so nodes are never compared
            for _ in range(k + 1):                  # the first k + 1 nodes
                if cur is None:
                    break
                heapq.heappush(heap, (cur.val, order, cur))
                order, cur = order + 1, cur.next
            new_head = tail = None
            while heap:
                _, _, mn = heapq.heappop(heap)      # the smallest of the next k + 1 must come next
                if new_head is None:
                    new_head, mn.prev = mn, None
                else:
                    tail.next, mn.prev = mn, tail
                tail = mn
                if cur is not None:
                    heapq.heappush(heap, (cur.val, order, cur))
                    order, cur = order + 1, cur.next
            tail.next = None
            return new_head

    Common mistakes

    • Using a heap of size k instead of k + 1, which can miss the smallest value.
    • Forgetting the prev links when relinking.
    • Not ending the list with tail.next = null.

    Similar problems