leetcode.com
Linked Lists keep finding new ways to test pointer manipulation. Today's problem looks simple at first glance, but the optimal solution comes from a powerful observation: instead of moving nodes one by one, convert the list into a circle and break it at the correct position.
Problem Statement
Given the head of a linked list, rotate the list to the right by k places.
Example
Input:
1 -> 2 -> 3 -> 4 -> 5
k = 2
Output:
4 -> 5 -> 1 -> 2 -> 3
Brute Force Intuition
A straightforward approach is:
Find the last node.
Remove it.
Insert it at the beginning.
Repeat this process k times.
For every rotation, we traverse almost the entire list to find the last node.
Interview Explanation
For each rotation, we move the last node to the front. Since finding the last node takes O(n), and we do this k times, the overall complexity be
Discussion
Break the silence
Take the opportunity to kick things off.