Open In App

Move the Kth Prime Number Node to the End of the Linked List

Given a singly linked list, the task is to move the Kth prime number node to the end of the list while preserving the order of other nodes.

Examples:



Input: 4 -> 7 -> 11 -> 3 -> 14 -> 2 -> NULL, K = 2
Output: 4 -> 7 -> 3 -> 14 -> 2 -> 11 -> NULL
Explanation: In the given list, the prime number nodes are 7, 11, 3, and 2. When K is set to 2, the second prime number node, which is 7, is moved to the end while maintaining the order of other nodes.

Input: 12 -> 6 -> 18 -> 5 -> 9 -> NULL, K = 1
Output: 12 -> 6 -> 18 -> 9 -> 5 -> NULL
Explanation: In this case, the prime number nodes are 5 and the K value is 1. As the first prime number which is 5 is moved to the end while maintaining the order of other nodes.



Approach: To solve the problem follow the below idea:

The approach begins by iterating through the linked list, identifying prime number nodes and storing them in a vector. When the Kth prime number is encountered, it is removed from its current position while maintaining the order of other nodes. Finally, the Kth prime number is appended to the end of the list. This approach ensures that the relative order of non-prime nodes remains the same. It combines prime number identification, list manipulation, and tracking the previous node to achieve the desired outcome, all while preserving the integrity of the original list structure.

Steps of the above approach:

Implementation of the above approach:




// C++ code for the above approach:
#include <iostream>
#include <vector>
 
using namespace std;
 
// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x)
        : val(x)
        , next(NULL)
    {
    }
};
 
// Function to check if a number
// is prime.
bool isPrime(int num)
{
    if (num <= 1)
        return false;
    if (num <= 3)
        return true;
    if (num % 2 == 0 || num % 3 == 0)
        return false;
 
    // Use a more efficient primality
    // test for larger numbers.
    for (int i = 5; i * i <= num; i += 6) {
        if (num % i == 0 || num % (i + 2) == 0)
            return false;
    }
 
    return true;
}
 
// Function to move the Kth prime
// number node to the end.
ListNode* moveKthPrimeToTheEnd(ListNode* head, int k)
{
    if (head == nullptr || k <= 0)
        return head;
 
    ListNode* curr = head;
    ListNode* prev = nullptr;
    vector<ListNode*> primes;
 
    // Traverse the list and find prime
    // numbers, storing them in a vector.
    while (curr) {
        if (isPrime(curr->val)) {
            primes.push_back(curr);
 
            // If we've found the Kth
            // prime, remove it from
            // the list and break the loop.
            if (primes.size() == k) {
                if (prev == nullptr) {
                    head = curr->next;
                }
                else {
                    prev->next = curr->next;
                }
                curr = curr->next;
                primes.back()->next = nullptr;
                break;
            }
            else {
                prev = curr;
                curr = curr->next;
            }
        }
        else {
            prev = curr;
            curr = curr->next;
        }
    }
 
    // Append the Kth prime
    // node to the end.
    if (k <= primes.size()) {
        if (prev) {
            prev->next = primes[k - 1];
        }
        else {
            head = primes[k - 1];
        }
    }
 
    return head;
}
 
// Function to print the linked list.
void printLinkedList(ListNode* head)
{
    while (head) {
        cout << head->val << " -> ";
        head = head->next;
    }
    cout << "NULL" << endl;
}
 
// Drivers code
int main()
{
    // Example 1:
    ListNode* head1 = new ListNode(4);
    head1->next = new ListNode(7);
    head1->next->next = new ListNode(11);
    head1->next->next->next = new ListNode(3);
    head1->next->next->next->next = new ListNode(14);
    head1->next->next->next->next->next = new ListNode(2);
 
    int k1 = 2;
 
    cout << "Example 1:" << endl;
    cout << "Original Linked List: ";
    printLinkedList(head1);
 
    // Move the Kth prime number to
    // the end of the linked
    // list for Example 1.
    head1 = moveKthPrimeToTheEnd(head1, k1);
 
    cout << "Modified Linked List: ";
    printLinkedList(head1);
 
    // Example 2:
    ListNode* head2 = new ListNode(12);
    head2->next = new ListNode(6);
    head2->next->next = new ListNode(18);
    head2->next->next->next = new ListNode(5);
    head2->next->next->next->next = new ListNode(9);
 
    int k2 = 1;
 
    cout << "Example 2:" << endl;
    cout << "Original Linked List: ";
    printLinkedList(head2);
 
    // Move the Kth prime number to
    // the end of the linked
    // list for Example 2.
    head2 = moveKthPrimeToTheEnd(head2, k2);
 
    cout << "Modified Linked List: ";
    printLinkedList(head2);
 
    return 0;
}




// Java Implementation
import java.util.ArrayList;
import java.util.List;
 
class ListNode {
    int val;
    ListNode next;
 
    ListNode(int x) {
        val = x;
        next = null;
    }
}
 
public class Main {
 
    public static boolean isPrime(int num) {
        if (num <= 1)
            return false;
        if (num <= 3)
            return true;
        if (num % 2 == 0 || num % 3 == 0)
            return false;
 
        for (int i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0)
                return false;
        }
 
        return true;
    }
 
    public static ListNode moveKthPrimeToTheEnd(ListNode head, int k) {
        if (head == null || k <= 0)
            return head;
 
        ListNode curr = head;
        ListNode prev = null;
        List<ListNode> primes = new ArrayList<>();
 
        while (curr != null) {
            if (isPrime(curr.val)) {
                primes.add(curr);
 
                if (primes.size() == k) {
                    if (prev == null) {
                        head = curr.next;
                    } else {
                        prev.next = curr.next;
                    }
                    curr = curr.next;
                    primes.get(primes.size() - 1).next = null;
                    break;
                } else {
                    prev = curr;
                    curr = curr.next;
                }
            } else {
                prev = curr;
                curr = curr.next;
            }
        }
 
        if (k <= primes.size()) {
            if (prev != null) {
                prev.next = primes.get(k - 1);
            } else {
                head = primes.get(k - 1);
            }
        }
 
        return head;
    }
 
    public static void printLinkedList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("NULL");
    }
 
    public static void main(String[] args) {
        ListNode head1 = new ListNode(4);
        head1.next = new ListNode(7);
        head1.next.next = new ListNode(11);
        head1.next.next.next = new ListNode(3);
        head1.next.next.next.next = new ListNode(14);
        head1.next.next.next.next.next = new ListNode(2);
 
        int k1 = 2;
 
        System.out.println("Example 1:");
        System.out.print("Original Linked List: ");
        printLinkedList(head1);
 
        head1 = moveKthPrimeToTheEnd(head1, k1);
 
        System.out.print("Modified Linked List: ");
        printLinkedList(head1);
 
        ListNode head2 = new ListNode(12);
        head2.next = new ListNode(6);
        head2.next.next = new ListNode(18);
        head2.next.next.next = new ListNode(5);
        head2.next.next.next.next = new ListNode(9);
 
        int k2 = 1;
 
        System.out.println("Example 2:");
        System.out.print("Original Linked List: ");
        printLinkedList(head2);
 
        head2 = moveKthPrimeToTheEnd(head2, k2);
 
        System.out.print("Modified Linked List: ");
        printLinkedList(head2);
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)




# Python code for moving the Kth prime number node to the end of a linked list
 
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
 
# Function to check if a number is prime.
def is_prime(num):
    if num <= 1:
        return False
    if num <= 3:
        return True
    if num % 2 == 0 or num % 3 == 0:
        return False
 
    # Use a more efficient primality
    # test for larger numbers.
    i = 5
    while i * i <= num:
        if num % i == 0 or num % (i + 2) == 0:
            return False
        i += 6
 
    return True
 
# Function to move the Kth prime number node to the end.
def move_kth_prime_to_end(head, k):
    if head is None or k <= 0:
        return head
 
    curr = head
    prev = None
    primes = []
 
    # Traverse the list and find prime
    # numbers, storing them in a list.
    while curr:
        if is_prime(curr.val):
            primes.append(curr)
 
            # If we've found the Kth
            # prime, remove it from
            # the list and break the loop.
            if len(primes) == k:
                if prev is None:
                    head = curr.next
                else:
                    prev.next = curr.next
                curr = curr.next
                primes[-1].next = None
                break
            else:
                prev = curr
                curr = curr.next
        else:
            prev = curr
            curr = curr.next
 
    # Append the Kth prime
    # node to the end.
    if k <= len(primes):
        if prev:
            prev.next = primes[k - 1]
        else:
            head = primes[k - 1]
 
    return head
 
# Function to print the linked list.
def print_linked_list(head):
    while head:
        print(str(head.val) + " -> ", end="")
        head = head.next
    print("NULL")
 
# Driver's code
if __name__ == "__main__":
    # Example 1:
    head1 = ListNode(4)
    head1.next = ListNode(7)
    head1.next.next = ListNode(11)
    head1.next.next.next = ListNode(3)
    head1.next.next.next.next = ListNode(14)
    head1.next.next.next.next.next = ListNode(2)
 
    k1 = 2
 
    print("Example 1:")
    print("Original Linked List: ", end="")
    print_linked_list(head1)
 
    # Move the Kth prime number to
    # the end of the linked
    # list for Example 1.
    head1 = move_kth_prime_to_end(head1, k1)
 
    print("Modified Linked List: ", end="")
    print_linked_list(head1)
 
    # Example 2:
    head2 = ListNode(12)
    head2.next = ListNode(6)
    head2.next.next = ListNode(18)
    head2.next.next.next = ListNode(5)
    head2.next.next.next.next = ListNode(9)
 
    k2 = 1
 
    print("Example 2:")
    print("Original Linked List: ", end="")
    print_linked_list(head2)
 
    # Move the Kth prime number to
    # the end of the linked
    # list for Example 2.
    head2 = move_kth_prime_to_end(head2, k2)
 
    print("Modified Linked List: ", end="")
    print_linked_list(head2)




// C# Implementation
using System;
using System.Collections.Generic;
 
public class ListNode
{
    public int val;
    public ListNode next;
 
    public ListNode(int x)
    {
        val = x;
        next = null;
    }
}
 
public class MainClass
{
    // Helper function to check if a number is prime
    public static bool IsPrime(int num)
    {
        if (num <= 1)
            return false;
        if (num <= 3)
            return true;
        if (num % 2 == 0 || num % 3 == 0)
            return false;
 
        for (int i = 5; i * i <= num; i += 6)
        {
            if (num % i == 0 || num % (i + 2) == 0)
                return false;
        }
 
        return true;
    }
 
    // Function to move the kth prime to the end of the linked list
    public static ListNode MoveKthPrimeToTheEnd(ListNode head, int k)
    {
        // Check for edge cases
        if (head == null || k <= 0)
            return head;
 
        ListNode curr = head;
        ListNode prev = null;
        List<ListNode> primes = new List<ListNode>();
 
        // Iterate through the linked list
        while (curr != null)
        {
            // If the current node's value is prime
            if (IsPrime(curr.val))
            {
                primes.Add(curr);
 
                // If k primes are found
                if (primes.Count == k)
                {
                    // Adjust pointers to exclude the kth prime from the linked list
                    if (prev == null)
                    {
                        head = curr.next;
                    }
                    else
                    {
                        prev.next = curr.next;
                    }
                    curr = curr.next;
                    primes[primes.Count - 1].next = null;
                    break;
                }
                else
                {
                    prev = curr;
                    curr = curr.next;
                }
            }
            else
            {
                prev = curr;
                curr = curr.next;
            }
        }
 
        // If there are at least k primes
        if (k <= primes.Count)
        {
            // Adjust pointers to include the kth prime at the end
            if (prev != null)
            {
                prev.next = primes[k - 1];
            }
            else
            {
                head = primes[k - 1];
            }
        }
 
        return head;
    }
 
    // Function to print the linked list
    public static void PrintLinkedList(ListNode head)
    {
        while (head != null)
        {
            Console.Write(head.val + " -> ");
            head = head.next;
        }
        Console.WriteLine("NULL");
    }
 
    public static void Main(string[] args)
    {
        // Example 1
        ListNode head1 = new ListNode(4);
        head1.next = new ListNode(7);
        head1.next.next = new ListNode(11);
        head1.next.next.next = new ListNode(3);
        head1.next.next.next.next = new ListNode(14);
        head1.next.next.next.next.next = new ListNode(2);
 
        int k1 = 2;
 
        Console.WriteLine("Example 1:");
        Console.Write("Original Linked List: ");
        PrintLinkedList(head1);
 
        head1 = MoveKthPrimeToTheEnd(head1, k1);
 
        Console.Write("Modified Linked List: ");
        PrintLinkedList(head1);
 
        // Example 2
        ListNode head2 = new ListNode(12);
        head2.next = new ListNode(6);
        head2.next.next = new ListNode(18);
        head2.next.next.next = new ListNode(5);
        head2.next.next.next.next = new ListNode(9);
 
        int k2 = 1;
 
        Console.WriteLine("Example 2:");
        Console.Write("Original Linked List: ");
        PrintLinkedList(head2);
 
        head2 = MoveKthPrimeToTheEnd(head2, k2);
 
        Console.Write("Modified Linked List: ");
        PrintLinkedList(head2);
    }
}
// This code is contributed By Sakshi




// JavaScript code for the above approach
 
// Definition for singly-linked list.
class ListNode {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}
 
// Function to check if a number is prime.
function isPrime(num) {
  if (num <= 1) return false;
  if (num <= 3) return true;
  if (num % 2 === 0 || num % 3 === 0) return false;
 
  // Use a more efficient primality test for larger numbers.
  for (let i = 5; i * i <= num; i += 6) {
    if (num % i === 0 || num % (i + 2) === 0) return false;
  }
 
  return true;
}
 
// Function to move the Kth prime number node to the end.
function moveKthPrimeToTheEnd(head, k) {
  if (!head || k <= 0) return head;
 
  let curr = head;
  let prev = null;
  const primes = [];
 
  // Traverse the list and find prime numbers, storing them in an array.
  while (curr) {
    if (isPrime(curr.val)) {
      primes.push(curr);
 
      // If we've found the Kth prime, remove it from the list and break the loop.
      if (primes.length === k) {
        if (prev === null) {
          head = curr.next;
        } else {
          prev.next = curr.next;
        }
        curr = curr.next;
        primes[primes.length - 1].next = null;
        break;
      } else {
        prev = curr;
        curr = curr.next;
      }
    } else {
      prev = curr;
      curr = curr.next;
    }
  }
 
  // Append the Kth prime node to the end.
  if (k <= primes.length) {
    if (prev) {
      prev.next = primes[k - 1];
    } else {
      head = primes[k - 1];
    }
  }
 
  return head;
}
 
// Function to print the linked list.
function printLinkedList(head) {
  let result = '';
  while (head) {
    result += head.val + ' -> ';
    head = head.next;
  }
  result += 'NULL';
  console.log(result);
}
 
// Example 1:
let head1 = new ListNode(4);
head1.next = new ListNode(7);
head1.next.next = new ListNode(11);
head1.next.next.next = new ListNode(3);
head1.next.next.next.next = new ListNode(14);
head1.next.next.next.next.next = new ListNode(2);
 
let k1 = 2;
 
console.log("Example 1:");
console.log("Original Linked List: ");
printLinkedList(head1);
 
// Move the Kth prime number to the end of the linked list for Example 1.
head1 = moveKthPrimeToTheEnd(head1, k1);
 
console.log("Modified Linked List: ");
printLinkedList(head1);
 
// Example 2:
let head2 = new ListNode(12);
head2.next = new ListNode(6);
head2.next.next = new ListNode(18);
head2.next.next.next = new ListNode(5);
head2.next.next.next.next = new ListNode(9);
 
let k2 = 1;
 
console.log("Example 2:");
console.log("Original Linked List: ");
printLinkedList(head2);
 
// Move the Kth prime number to the end of the linked list for Example 2.
head2 = moveKthPrimeToTheEnd(head2, k2);
 
console.log("Modified Linked List: ");
printLinkedList(head2);

Output
Example 1:
Original Linked List: 4 -> 7 -> 11 -> 3 -> 14 -> 2 -> NULL
Modified Linked List: 4 -> 7 -> 11 -> NULL
Example 2:
Original Linked List: 12 -> 6 -> 18 -> 5 -> 9 -> NULL
Modified Linked List: ...








Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(K), where K is the value of the input parameter k. This is because we maintain a vector “primes” to store prime number nodes up to the Kth prime.


Article Tags :