Approach :
So, did you try to solve this problem on your own? There is this trick here in the constraints that you cannot solve the problem by using the size property. Otherwise, it would have been a piece of cake, right? So, the solution to this problem is called the Two Pointer Approach and it is not only used in this problem, but it is used in many problems. Let us try to understand the basis of this two pointer approach first in a fun way. The Idea Behind The Two Pointer Approach: Let us consider a racing track (500m long). Let us say there are two people. They are you and me. So, my friend, you and I are on a racing track and the race has not started yet. You are already standing at the 200m spot while I am at the starting position i.e. the 0m spot. (Have a look at fig-4) Input: 1 -> 2 -> 3 -> 4 -> 5, K = 5 Approach: To solve the problem follow the below idea:
Below is the implementation of the above approach:
OutputOriginal Linked List: 1 2 3 4 5 6 7 8 Modified List for k = 1 8 2 3 4 5 6 7 1 Modified List for k = 2 8 7 3 4 5 6 2 1 Modified List for k = 3 8 7 6 4 5 3 2 1 Modified List for k = 4 8 7 6 5 4 3 2 1 Modified List for k = 5 8 7 6 4 5 3 2 1 Modified List for k = 6 8 7 3 4 5 6 2 1 Modified List for k = 7 8 2 3 4 5 6 7 1 Modified List for k = 8 1 2 3 4 5 6 7 8 Time Complexity: O(N), where N is the length of the list. One traversal of the list is needed. Please note that the above code runs three separate loops to count nodes, find x and x prev, and to find y and y_prev. These three things can be done in a single loop. The code uses three loops to keep things simple and readable. |