Link List sum and Prime Insertion
Last Updated :
07 May, 2024
Given the head of a singly linked list, the task is to perform the following operations:
- Sum the values of adjacent nodes, i.e., the current node and its next node.
- Insert the nearest prime number to the sum between the two adjacent nodes.
Note: If more than one prime number exists at an equal distance, choose the smallest one.
Examples:
Input: Linked list: 2 → 4 → 7 → 5 → 9
Output: 2 → 5 → 4 → 11 → 7 → 11 → 5 → 13 → 9
Explanation: The sum of the first adjacent pair of 2 and 4 is 6 and the nearest prime number of 6 is 5 and 7 at equal distance so insert 5 between 2 and 4. The sum of the second adjacent pair of 4 and 7 is 11 and the nearest prime number of 11 is 11 so insert 11 between 4 and 7. The sum of the Third adjacent pair of 7 and 5 is 12 and the nearest prime number of 12 is 11 and 13 at an equal distance so insert 11 between 7 and 5, and so on… At last, the resultant linked list will be 2 → 5 → 4 → 11 → 7 → 11 → 5 → 13 → 9.
Input: Linked list: 3 → 5 → 9 → 7
Output: 3 → 7 → 5 → 13 → 9 → 17 → 7
Explanation: The sum of the first adjacent pair of 3 and 5 is 8 and the nearest prime number of 8 is 7 so insert 7 between 3 and 5. The sum of the second adjacent pair of 5 and 9 is 14 and the nearest prime number of 14 is 13 so insert 13 between 5 and 9. The sum of the Third adjacent pair of 9 and 7 is 16 and the nearest prime number of 16 is 17 so insert 17 between 9 and 7. At last the resultant linked list will be 3 → 7 → 5 → 13 → 9 → 17 → 7
Approach: To solve the problem follow the below idea:
Idea is to traverse the Linked List using two pointers and sum up them then check for if the sum is a prime number, if the sum is itself a nearest prime number for it, so insert the sum between two adjacent nodes, if the sum is not a prime number, find nearest prime number for the sum and insert that prime number between them and move forward.
Below are the steps for the above approach:
- Initialize two pointers, p1 and p2, to the first and second nodes in the linked list, respectively.
- Iterate through the linked list:
- Calculate the sum of the values of the current node (p1) and the next node (p2).
- Find the nearest prime number to sum using the nearestPrime function.
- Create a new node with the value of the nearest prime (p) and insert it between p1 and p2 in the linked list.
- Update p1 to point to the newly inserted node and p2 to point to the node after it (Moving the p1 and p2).
Finding nearest prime number:
- Check if the input number num is already a prime number using the sieve of erotathenes. If it is, return num as the nearest prime.
- If num is less than or equal to 1, return 2 because the nearest prime to 1 is 2.
- Initialize two variables, lower and upper, to num – 1 and num + 1, respectively.
- Iterate on loop until a prime number is found.
- Check if lower is a prime number using the isPrime function. If it is, return lower as the nearest prime.
- If lower is not prime, check if upper is a prime number. If it is, return upper as the nearest prime.
- If both lower and upper are not prime, decrement lower by 1 and increment upper by 1.
Below is the implementation for the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int num)
{
data = num;
next = NULL;
}
};
// Function to generate prime numbers
// using Sieve of Eratosthenes
vector<bool> isPrime;
void sieve(int n)
{
isPrime.resize(n + 1, true);
isPrime[0] = isPrime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (isPrime[p]) {
for (int i = p * p; i <= n; i += p) {
isPrime[i] = false;
}
}
}
}
// Function for finding the nearest
// prime number
int nearestPrime(int num)
{
// if num is already prime number
if (isPrime[num])
return num;
// The nearest prime to 1 is 2.
if (num <= 1)
return 2;
int lower = num - 1;
int upper = num + 1;
while (true) {
// If lower is prime, return it
// as the nearest prime.
if (isPrime[lower]) {
return lower;
}
// If upper is prime, return it
// as the nearest prime.
if (isPrime[upper]) {
return upper;
}
lower--;
upper++;
}
}
// Function for Summing Adjacent Linked List
// Nodes and Inserting Nearest Prime Sums
void insertPrime(Node* head)
{
Node* p1 = head;
Node* p2 = head->next;
while (p2 != NULL) {
// Sum of two adjacent nodes
int sum = p1->data + p2->data;
// Calculate the nearest prime to the
// sum of two nodes' values.
int p = nearestPrime(sum);
// Create a new node with the
// nearest prime value.
Node* temp = new Node(p);
// Insert the new node between p1 and p2
p1->next = temp;
temp->next = p2;
p1 = temp->next;
p2 = p2->next;
}
}
// Function for Printing linked list
void printList(Node* head)
{
Node* cur = head;
while (cur->next != NULL) {
cout << cur->data << " -> ";
cur = cur->next;
}
cout << cur->data;
}
// Driver code
int main()
{
// Set the maximum number for
// prime generation
int maxNum = 100;
sieve(maxNum);
// Your existing code for
// linked list and insertion
Node* head = new Node(2);
head->next = new Node(4);
head->next->next = new Node(7);
head->next->next->next = new Node(5);
head->next->next->next->next = new Node(9);
// Given linked list
cout << "Given Linked List: ";
printList(head);
cout << endl;
// Function call for inserting nearest prime
insertPrime(head);
cout << "Resultant Linked List: ";
// Resultant linked list is
printList(head);
return 0;
}
Java
import java.util.*;
class Node {
public int data;
public Node next;
public Node(int num) {
data = num;
next = null;
}
}
public class Main {
static List<Boolean> isPrime;
// Function to generate prime numbers using Sieve of Eratosthenes
static void sieve(int n) {
isPrime = new ArrayList<>(Collections.nCopies(n + 1, true));
isPrime.set(0, false);
isPrime.set(1, false);
for (int p = 2; p * p <= n; p++) {
if (isPrime.get(p)) {
for (int i = p * p; i <= n; i += p) {
isPrime.set(i, false);
}
}
}
}
// Function for finding the nearest prime number
static int nearestPrime(int num) {
// If num is already a prime number
if (isPrime.get(num))
return num;
// The nearest prime to 1 is 2
if (num <= 1)
return 2;
int lower = num - 1;
int upper = num + 1;
while (true) {
// If lower is prime, return it as the nearest prime
if (isPrime.get(lower)) {
return lower;
}
// If upper is prime, return it as the nearest prime
if (isPrime.get(upper)) {
return upper;
}
lower--;
upper++;
}
}
// Function for summing adjacent linked list nodes and inserting nearest prime sums
static void insertPrime(Node head) {
Node p1 = head;
Node p2 = head.next;
while (p2 != null) {
// Sum of two adjacent nodes
int sum = p1.data + p2.data;
// Calculate the nearest prime to the sum of two nodes' values
int p = nearestPrime(sum);
// Create a new node with the nearest prime value
Node temp = new Node(p);
// Insert the new node between p1 and p2
p1.next = temp;
temp.next = p2;
p1 = temp.next;
p2 = p2.next;
}
}
// Function for printing linked list
static void printList(Node head) {
Node cur = head;
while (cur.next != null) {
System.out.print(cur.data + " -> ");
cur = cur.next;
}
System.out.println(cur.data);
}
public static void main(String[] args) {
// Set the maximum number for prime generation
int maxNum = 100;
sieve(maxNum);
// Your existing code for linked list and insertion
Node head = new Node(2);
head.next = new Node(4);
head.next.next = new Node(7);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(9);
// Given linked list
System.out.print("Given Linked List: ");
printList(head);
// Function call for inserting nearest prime
insertPrime(head);
System.out.print("Resultant Linked List: ");
// Resultant linked list
printList(head);
}
}
Python
class Node:
def __init__(self, num):
self.data = num
self.next = None
# Function to generate prime numbers using Sieve of Eratosthenes
def sieve(n):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for p in range(2, int(n**0.5) + 1):
if is_prime[p]:
for i in range(p * p, n + 1, p):
is_prime[i] = False
return is_prime
# Function for finding the nearest prime number
def nearest_prime(num, is_prime):
# If num is already a prime number
if is_prime[num]:
return num
# The nearest prime to 1 is 2
if num <= 1:
return 2
lower = num - 1
upper = num + 1
while True:
# If lower is prime, return it as the nearest prime
if is_prime[lower]:
return lower
# If upper is prime, return it as the nearest prime
if is_prime[upper]:
return upper
lower -= 1
upper += 1
# Function for summing adjacent linked list nodes and inserting nearest prime sums
def insert_prime(head, is_prime):
p1 = head
p2 = head.next
while p2 is not None:
# Sum of two adjacent nodes
_sum = p1.data + p2.data
# Calculate the nearest prime to the sum of two nodes' values
p = nearest_prime(_sum, is_prime)
# Create a new node with the nearest prime value
temp = Node(p)
# Insert the new node between p1 and p2
p1.next = temp
temp.next = p2
p1 = temp.next
p2 = p2.next
# Function for printing linked list
def print_list(head):
current = head
while current.next is not None:
print(current.data, end=" -> ")
current = current.next
print(current.data)
if __name__ == "__main__":
# Set the maximum number for prime generation
max_num = 100
is_prime = sieve(max_num)
# Your existing code for linked list and insertion
head = Node(2)
head.next = Node(4)
head.next.next = Node(7)
head.next.next.next = Node(5)
head.next.next.next.next = Node(9)
# Given linked list
print("Given Linked List:", end=" ")
print_list(head)
# Function call for inserting nearest prime
insert_prime(head, is_prime)
print("Resultant Linked List:", end=" ")
# Resultant linked list
print_list(head)
C#
using System;
public class Node
{
public int data;
public Node next;
public Node(int num)
{
data = num;
next = null;
}
}
public class MainClass
{
// Function to generate prime numbers using Sieve of Eratosthenes
static bool[] Sieve(int n)
{
bool[] isPrime = new bool[n + 1];
for (int i = 0; i <= n; i++)
{
isPrime[i] = true;
}
isPrime[0] = isPrime[1] = false;
for (int p = 2; p * p <= n; p++)
{
if (isPrime[p])
{
for (int i = p * p; i <= n; i += p)
{
isPrime[i] = false;
}
}
}
return isPrime;
}
// Function for finding the nearest prime number
static int NearestPrime(int num, bool[] isPrime)
{
// If num is already a prime number
if (num >= 0 && num < isPrime.Length && isPrime[num])
return num;
// The nearest prime to 1 is 2
if (num <= 1)
return 2;
int lower = num - 1;
int upper = num + 1;
while (true)
{
// If lower is prime, return it as the nearest prime
if (lower >= 0 && lower < isPrime.Length && isPrime[lower])
return lower;
// If upper is prime, return it as the nearest prime
if (upper < isPrime.Length && isPrime[upper])
return upper;
lower--;
upper++;
}
}
// Function for summing adjacent linked list nodes and inserting nearest prime sums
static void InsertPrime(Node head, bool[] isPrime)
{
Node p1 = head;
Node p2 = head.next;
while (p2 != null)
{
// Sum of two adjacent nodes
int sum = p1.data + p2.data;
// Calculate the nearest prime to the sum of two nodes' values
int p = NearestPrime(sum, isPrime);
// Create a new node with the nearest prime value
Node temp = new Node(p);
// Insert the new node between p1 and p2
p1.next = temp;
temp.next = p2;
p1 = temp.next;
p2 = p2.next;
}
}
// Function for printing linked list
static void PrintList(Node head)
{
Node current = head;
while (current.next != null)
{
Console.Write(current.data + " -> ");
current = current.next;
}
Console.WriteLine(current.data);
}
public static void Main()
{
// Set the maximum number for prime generation
int maxNum = 100;
bool[] isPrime = Sieve(maxNum);
// Your existing code for linked list and insertion
Node head = new Node(2);
head.next = new Node(4);
head.next.next = new Node(7);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(9);
// Given linked list
Console.Write("Given Linked List: ");
PrintList(head);
Console.WriteLine();
// Function call for inserting nearest prime
InsertPrime(head, isPrime);
Console.Write("Resultant Linked List: ");
// Resultant linked list
PrintList(head);
}
}
Javascript
class Node {
constructor(num) {
this.data = num;
this.next = null;
}
}
let isPrime = [];
// Function to generate prime numbers using Sieve of Eratosthenes
function sieve(n) {
isPrime = new Array(n + 1).fill(true);
isPrime[0] = isPrime[1] = false;
for (let p = 2; p * p <= n; p++) {
if (isPrime[p]) {
for (let i = p * p; i <= n; i += p) {
isPrime[i] = false;
}
}
}
}
// Function for finding the nearest prime number
function nearestPrime(num) {
if (isPrime[num]) return num;
if (num <= 1) return 2;
let lower = num - 1;
let upper = num + 1;
while (true) {
if (isPrime[lower]) return lower;
if (isPrime[upper]) return upper;
lower--;
upper++;
}
}
// Function for summing adjacent linked list nodes and inserting nearest prime sums
function insertPrime(head) {
let p1 = head;
let p2 = head.next;
while (p2 !== null) {
const sum = p1.data + p2.data;
const nearest = nearestPrime(sum);
const temp = new Node(nearest);
p1.next = temp;
temp.next = p2;
p1 = temp.next;
p2 = p2.next;
}
}
// Function for printing linked list
function printList(head) {
let cur = head;
while (cur.next !== null) {
console.log(cur.data + ' -> ');
cur = cur.next;
}
console.log(cur.data);
}
// Driver code
function main() {
const maxNum = 100;
sieve(maxNum);
const head = new Node(2);
head.next = new Node(4);
head.next.next = new Node(7);
head.next.next.next = new Node(5);
head.next.next.next.next = new Node(9);
console.log('Given Linked List: ');
printList(head);
console.log('');
insertPrime(head);
console.log('Resultant Linked List: ');
printList(head);
}
main();
//This code is contributed by Vikram_Shirsat
OutputGiven Linked List: 2 -> 4 -> 7 -> 5 -> 9
Resultant Linked List: 2 -> 5 -> 4 -> 11 -> 7 -> 11 -> 5 -> 13 -> 9
Time Complexity: O(n*sqrt(maxNum)), where n is the length of linked list and sqrt(maxNum) for finding nearest prime number.
Auxiliary Space: O(m), where m is new nodes added to the input linked list.
Share your thoughts in the comments
Please Login to comment...