DSA AnimatorREVISION VIDEOS
← Back to problems
New

Reverse Linked List II — LeetCode 92 video explanation

Reverse only the nodes from position left to position right. Positions start at 1, and the rest of the list stays in place.

Loading videos…

DSA Animator › DSA Revision › Linked List › Reverse Linked List II

Key moments in the Reverse Linked List II video

0:03Problem0:11Example0:17Brute force0:26Key idea0:37Dry run0:49Code1:03Takeaway

What you will learn

Remember: fix previous before the section and keep moving the next node to the front. Current slides to the back by itself. The video solves Reverse Linked List II (LeetCode 92, Medium) with the Pointer Reversal pattern from the Linked List topic, and you can replay every step in the interactive Reverse Linked List II animation.

Reverse Linked List II video transcript

Problem

Reverse only the nodes from position left to position right. Positions start at 1, and the rest of the list stays in place.

Example

For 1, 2, 3, 4, 5 with left 2 and right 4, the result is 1, 4, 3, 2, 5.

Brute force

Copying the values into an array, reversing that slice, and writing them back works. But it uses extra space, and we can relink in place.

Key idea

Walk a pointer, previous, to the node just before position left. Then, again and again, take the node after current and move it to the front of the section. Repeat right minus left times.

Dry run

Previous stops at 1, and current is 2. Move 3 to the front, after 1, giving 1, 3, 2, 4, 5. Move 4 to the front, giving 1, 4, 3, 2, 5. Two moves were needed, so we are done.

Code

In code, use a dummy head and move previous left minus 1 steps. In a loop, take the node after current, unlink it, and insert it right after previous. Return dummy dot next, so it's one pass and O of 1 space.

Takeaway

Remember: fix previous before the section and keep moving the next node to the front. Current slides to the back by itself.

More Linked List revision videos

← All 185 DSA revision videos