Open In App

Minimize first node of Linked List by deleting first or adding one deleted node at start

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Examples:

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: 

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of node of singly linked list
struct Node {
    int data;
    Node* next;
    Node(int x)
    {
        data = x;
        next = NULL;
    }
};
 
// Inserting new node
// at the  beginning of the linked list
void push(struct Node** head_ref,
          int new_data)
{
    // Create a new node with the given data.
    struct Node* new_node = new Node(new_data);
 
    // Make the new node point to the head.
    new_node->next = (*head_ref);
 
    // Make the new node as the head node.
    (*head_ref) = new_node;
}
 
// Function to find the
// minimum possible first node
int FirstNode(Node* head, int K)
{
    if (K == 0) {
        return head->data;
    }
    if (K == 1) {
        return (head->next == NULL) ? -1 : head->next->data;
    }
    if (head->next == NULL) {
        return (K % 2) ? -1 : head->data;
    }
    int ans = INT_MAX;
    int i = 0;
 
    // Traverse 1st K-1 Nodes and find out
    // minimum node
    // value
    while (head != NULL && i < K - 1) {
        if (head->data < ans)
            ans = head->data;
        head = head->next;
        i++;
    }
 
    // Check whether Linked list have (K+1)th
    // Node or not
    if (head && head->next != NULL) {
 
        // Update ans with minimum of 1st K-1
        // nodes and the (K+1)th Node.
        ans = min(ans, head->next->data);
    }
    return ans;
}
 
// Driver code
int main()
{
    int K = 4;
 
    // Create an empty singly linked list
    struct Node* head = NULL;
 
    // Insert values in Linked List
    push(&head, 3);
    push(&head, 5);
    push(&head, 2);
    push(&head, 4);
    push(&head, 1);
 
    // Call FirstNode function
    cout << FirstNode(head, K);
    return 0;
}


Java




// Java Program for the above approach
 
import java.io.*;
 
class GFG {
 
      // structure of a node.
    class Node {
        int data;
        Node next;
        Node(int data)
        {
            this.data = data;
            this.next = null;
        }
    }
     
      // Creating a head node.
      Node head;
       
      // Inserting nodes into linked list.
    public void push(int data)
    {
        Node new_node = new Node(data);
        new_node.next = head;
        head = new_node;
    }
 
      // Method to find the minimum possible time.
    public int firstNode(int k)
    {
        int ans = Integer.MAX_VALUE;
        int i = 0;
        if (k == 0) {
            return head.data;
        }
        if (k == 1) {
            return (head.next == null) ? -1
                                       : head.next.data;
        }
        if (head.next == null) {
            if (k % 2 == 1) {
                return -1;
            }
            return head.data;
        }
 
        while (head != null && (i < k - 1)) {
            if (head.data < ans) {
                ans = head.data;
            }
            head = head.next;
            i++;
        }
        if (head != null && head.next != null) {
            ans = Math.min(ans, head.next.data);
        }
        return ans;
    }
 
    public static void main(String[] args)
    {
        GFG list = new GFG();
 
          // Insert values in linked list.
        list.push(3);
        list.push(5);
        list.push(2);
        list.push(4);
        list.push(1);
 
        int k = 4;
        System.out.print(list.firstNode(k));
    }
}
 
// This code is contributed by lokesh (lokeshmvs21).


Python3




# Python code for the above approach
 
# Node Class
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None
             
 
class LinkedList:
    def __init__(self):
        self.head = None
 
    ## Inserting new node
    ## at the beginning of the linked list
    def push(self, new_data):
 
        ## Create a new node with the given data.
        new_node = Node(new_data)
 
        ## Make the new node point to the head.
        new_node.next = self.head
 
        ## Make the new node as the head node.
        self.head = new_node
 
    ## Function to find the
    ## minimum possible first node
    def FirstNode(self, K):
        if(K == 0):
            return self.head.data
        elif (K == 1):
            if (self.head.next == None):
                return -1
            return  self.head.next.data
        elif (self.head.next == None):
            if(K%2==1):
                return -1
            return self.head.data
        ## Initialize answer with Infinity
        ans = 1000000000000000000
        i = 0
 
        ## Traverse 1st K-1 nodes and find out
        ## minimum node value
        while(self.head != None and i < (K-1)):
            if(self.head.data < ans):
                ans = self.head.data
            self.head = self.head.next
            i+=1
         
        ## Check whether Linked list have (K+1)th
        ## Node or not
        if(self.head != None and self.head.next != None):
 
            ## Update ans with minimum of 1st K-1
            ## nodes and the (K+1)th Node.
            ans = min(ans, self.head.next.data)
         
        return ans
 
 
# Driver Code
if __name__=='__main__':
 
    K = 4
 
    ## Create an empty singly linked list
    llist = LinkedList()
 
    llist.push(3)
    llist.push(5)
    llist.push(2)
    llist.push(4)
    llist.push(1)
 
    ## Call FirstNode function
    print(llist.FirstNode(K))
 
    # This code is contributed by subhamgoyal2014.


C#




// C# program for the above approach
using System;
 
public class GFG {
 
    // Structure of a node.
    class Node {
        public int data;
        public Node next;
        public Node(int data)
        {
            this.data = data;
            this.next = null;
        }
    }
 
    // Creating a head node.
    Node head;
 
    // Inserting nodes into linked list.
    public void push(int data)
    {
        Node new_node = new Node(data);
        new_node.next = head;
        head = new_node;
    }
 
    // Function to find the minimum possible time.
    public int firstNode(int k)
    {
        int ans = Int32.MaxValue;
        int i = 0;
        if (k == 0) {
            return head.data;
        }
        if (k == 1) {
            return (head.next == null) ? -1
                                       : head.next.data;
        }
        if (head.next == null) {
            if (k % 2 == 1) {
                return -1;
            }
            return head.data;
        }
        while (head != null && (i < k - 1)) {
            if (head.data < ans) {
                ans = head.data;
            }
            head = head.next;
            i++;
        }
        if (head != null && head.next != null) {
            ans = Math.Min(ans, head.next.data);
        }
        return ans;
    }
 
    static public void Main()
    {
 
        // Code
        GFG list = new GFG();
 
        // Insert values in linked list.
        list.push(3);
        list.push(5);
        list.push(2);
        list.push(4);
        list.push(1);
 
        int k = 4;
        Console.WriteLine(list.firstNode(k));
    }
}
 
// This code is contributed by lokesh (lokeshmvs21).


Javascript




<script>
 
// JavaScript code for the above approach
 
// Node Class
class Node{
    constructor(d){
        this.data = d
        this.next = null
    }
}
             
class LinkedList{
    constructor(){
        this.head = null
    }
 
    // Inserting new node
    // at the beginning of the linked list
    push(new_data){
 
        // Create a new node with the given data.
        let new_node = new Node(new_data)
 
        // Make the new node point to the head.
        new_node.next = this.head
 
        // Make the new node as the head node.
        this.head = new_node
    }
 
    // function to find the
    // minimum possible first node
    FirstNode(K){
        if(K == 0)
            return this.head.data
        else if (K == 1){
            if (this.head.next == null)
                return -1
            return  this.head.next.data
        }
        else if (this.head.next == null){
            if(K%2==1)
                return -1
            return this.head.data
        }
        // Initialize answer with Infinity
        let ans = 1000000000000000000
        let i = 0
 
        // Traverse 1st K-1 nodes and find out
        // minimum node value
        while(this.head != null && i < (K-1)){
            if(this.head.data < ans)
                ans = this.head.data
            this.head = this.head.next
            i+=1
        }
        // Check whether Linked list have (K+1)th
        // Node or not
        if(this.head != null && this.head.next != null)
 
            // Update ans with minimum of 1st K-1
            // nodes and the (K+1)th Node.
            ans = Math.min(ans, this.head.next.data)
         
        return ans
    }
}
 
 
// Driver Code
 
let K = 4
 
// Create an empty singly linked list
let llist = new LinkedList()
 
llist.push(3)
llist.push(5)
llist.push(2)
llist.push(4)
llist.push(1)
 
// Call FirstNode function
document.write(llist.FirstNode(K),"</br>")
 
// This code is contributed by shinjanpatra
 
</script>


Output

1

Time Complexity: O(K)
Auxiliary Space: O(1)



Last Updated : 18 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads