Delete nodes which have a greater value on right side

Pattern: Reversal

medium

A node survives only if nothing to its right is bigger. Reverse the list so "to the right" becomes "already seen", keep a running maximum while deleting smaller nodes, then reverse back.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given the head of a linked list, delete every node that has a node with a strictly greater value somewhere to its right, and return the head. For example, 12 → 15 → 10 → 11 → 5 → 6 → 2 → 3 becomes 15 → 11 → 6 → 3, and an increasing list keeps only its last node.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name deleteNodes is this guide's own. Equal values do not count as greater, so 3 → 3 → 3 stays as it is.

Think first

  • A node survives exactly when it is at least as big as everything after it. What would you need to know at each node?
  • Walking forwards, you do not know the future. What if you walked from the right?
  • How can you walk from the right in a singly linked list?

Hints

    Brute force, and why it fails

    For each node, scan everything after it for a bigger value: O(n²). A stack can do it in one forward pass with O(n) memory. Reverse, scan, reverse uses O(1) memory.

    The key insight

    Questions about "everything to the right" become questions about "everything seen so far" after a reversal. A running maximum answers those in O(1) per node.

    Dry run

    30 
    21 
    62 
    53 
    114 
    105 
    156 
    127 
    best3

    The list is 12 → 15 → 10 → 11 → 5 → 6 → 2 → 3. Reverse it to 3 → 2 → 6 → 5 → 11 → 10 → 15 → 12.

    Step 1 of 4

    The plan

    rev = reverse(head)
    best = rev.val, cur = rev
    while cur.next is not null:
        if cur.next.val < best: cur.next = cur.next.next
        else: cur = cur.next; best = cur.val
    return reverse(rev)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two reversals and one scan.

    Edge cases

    • Decreasing list: unchanged.
    • Increasing list: only the last node.
    • Equal values: all kept.
    I've built my logic, show the code

    Java

    class Solution {
        public ListNode deleteNodes(ListNode head) {
            ListNode rev = reverse(head);           // walk from the right end
            int best = rev.val;                     // the largest value seen so far, from the right
            for (ListNode cur = rev; cur.next != null; ) {
                if (cur.next.val < best) cur.next = cur.next.next;   // something to its right is bigger: drop it
                else { cur = cur.next; best = cur.val; }              // keep it, it is the new largest
            }
            return reverse(rev);                    // back to the original direction
        }
    
        private ListNode reverse(ListNode head) {
            ListNode prev = null;
            while (head != null) { ListNode next = head.next; head.next = prev; prev = head; head = next; }
            return prev;
        }
    }

    C++

    class Solution {
    public:
        ListNode* deleteNodes(ListNode* head) {
            ListNode* rev = reverse(head);          // walk from the right end
            int best = rev->val;                    // the largest value seen so far, from the right
            for (ListNode* cur = rev; cur->next != NULL; ) {
                if (cur->next->val < best) cur->next = cur->next->next;   // something to its right is bigger: drop it
                else { cur = cur->next; best = cur->val; }                 // keep it, it is the new largest
            }
            return reverse(rev);                    // back to the original direction
        }
    
        ListNode* reverse(ListNode* head) {
            ListNode* prev = NULL;
            while (head != NULL) { ListNode* next = head->next; head->next = prev; prev = head; head = next; }
            return prev;
        }
    };

    Python

    from lib import ListNode
    
    class Solution:
        def deleteNodes(self, head: ListNode) -> ListNode:
            rev = self.reverse(head)                # walk from the right end
            best, cur = rev.val, rev                # the largest value seen so far, from the right
            while cur.next is not None:
                if cur.next.val < best:
                    cur.next = cur.next.next        # something to its right is bigger: drop it
                else:
                    cur = cur.next                  # keep it, it is the new largest
                    best = cur.val
            return self.reverse(rev)                # back to the original direction
    
        def reverse(self, head: ListNode) -> ListNode:
            prev = None
            while head is not None:
                head.next, prev, head = prev, head, head.next
            return prev

    Common mistakes

    • Using ≤ instead of <, which deletes equal values.
    • Forgetting to reverse back, which returns the survivors backwards.
    • Moving cur after a deletion, which skips a node.

    Similar problems