Given a singly linked list, and an integer K, the task is to make the first node value as minimum as possible in K operations where in each operation:
Select the first node of the linked list and remove it.
Add a previously removed node at the start of the linked list.
Input: list: 1->4->2->5->3, K=4 Output:1 Explanation: 1st operation-> Remove 1st Node, After performing operation linked list become 4->2->5->3 2nd operation-> Remove 1st Node, After performing operation linked list become 2->5->3 3rd operation-> Remove 1st Node, After performing operation linked list become 5->3 4th operation-> Add previously removed Node (i.e. 1), After performing operation linked list become 1->5->3
Input: Linked List: 5, K = 1 Output: -1 Explanation: Only possible operation is to delete the first node. If that operation is performed then the list will be empty.
Approach: The problem can be solved by using below observation:
In first K-1 operations, the K-1 value of the starting can be removed. So currently at Kth node. Now in the last operation there are two possible choice:
Either remove the current starting node (optimal if the value of the (K+1)th node is smaller than the smallest amongst first K-1 already removed elements)
Add the smallest from the already removed K-1 elements (optimal when the (K+1)th node has higher value than the smallest one)
Follow the below steps to solve the problem:
If K = 0, then return First Node Value.
If K = 1, then return Second Node value(if any) else return -1 (because after K operations the list does not exist).
If the size of the linked list is one then in every odd operation (i.e. 1, 3, 5, . . . ), return -1, else return the first node value (for the same reason as above).
If K > 2, then:
Traverse first K-1 nodes and find out the minimum value.
Compare that minimum value with the (K+1)th node value.
If (K+1)th value is less than the previous minimum value, update it with (K+1)th Node value.
Return the minimum value.
Below is the implementation of the above approach:
Please Login to comment...