DSA and coding Level 2 This level · 16 of 30
Medium dsa linked-lists

Reverse Linked List II

The 30 second answer

I walk to the node just before position left, then I reverse the next right minus left + 1 nodes by repeatedly taking the following node and moving it to the front of that span. A dummy head covers the case where left is 1, so the original head may change.

Could you say this in an interview?

Problem Reverse the nodes of a list from position left to position right, inclusive, and return the head. Positions are 1-based, and left is less than or equal to right. Original: LeetCode 92: Reverse Linked List II.

Understanding the prompt Only the closed interval [left, right] is reversed; the prefix and suffix stay as they are. If left is 1, the head of the list changes. You should do it in one pass and in place.

Pattern recognition In-place linked-list reversal of a sublist, with a dummy head so the start of the reversed span is easy to reattach.

Brute force Copy the sublist values into an array, reverse the array, and write them back: extra memory and two walks of the span.

Optimal dummy.next = head. Walk prev to the node at index left - 1. cur is the first node of the span and will stay the tail of the reversed piece. For each of the next right - left nodes, detach cur.next (call it move), insert move just after prev, and keep cur attached to the remainder. Return dummy.next.

Alternatives Reverse the whole list is the simpler form already answered on Kuchup; this is that routine with a bounded span. Reverse Nodes in k-Group repeats a similar span reversal.

Java solution

public class ReverseLinkedListII {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static ListNode list(int... a) {
        var dummy = new ListNode(0);
        var t = dummy;
        for (int x : a) {
            t.next = new ListNode(x);
            t = t.next;
        }
        return dummy.next;
    }

    static String str(ListNode h) {
        var sb = new StringBuilder("[");
        for (ListNode p = h; p != null; p = p.next) {
            if (sb.length() > 1) sb.append(", ");
            sb.append(p.val);
        }
        return sb.append("]").toString();
    }

    static ListNode reverseBetween(ListNode head, int left, int right) {
        var dummy = new ListNode(0, head);
        var prev = dummy;
        for (int i = 1; i < left; i++) prev = prev.next;
        var cur = prev.next;
        for (int i = 0; i < right - left; i++) {
            var move = cur.next;
            cur.next = move.next;
            move.next = prev.next;
            prev.next = move;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        System.out.println(str(reverseBetween(list(1, 2, 3, 4, 5), 2, 4))); // [1, 4, 3, 2, 5]
        System.out.println(str(reverseBetween(list(5), 1, 1)));              // [5]
        System.out.println(str(reverseBetween(list(1, 2, 3), 1, 3)));        // [3, 2, 1]
    }
}

Complexity O(n) time, O(1) extra space.

Edge cases

  • Official samples: [1,2,3,4,5] with left = 2 and right = 4 becomes [1,4,3,2,5]; [5] with left = right = 1 stays [5].
  • left = 1 and right = n reverses the whole list, as in [1,2,3] becoming [3,2,1].

Follow-ups

  • Reverse a whole list, and reverse in groups of k, are already answered on Kuchup's linked list pages.
  • Reverse even or odd positions is a close variant of the same rewiring.

Tests [1,2,3,4,5] from 2 to 4 becomes [1,4,3,2,5]. [5] from 1 to 1 stays [5]. [1,2,3] from 1 to 3 becomes [3,2,1].

How to say it in the interview "I walk to the node before left, then I reverse the sublist by pulling each next node to the front of that span. A dummy head covers the case where left is 1. One pass, constant space."

Sources (1)
  1. LeetCode 92: Reverse Linked List IIleetcode.com
Previous
Next