Open In App

Replace the values of the nodes with the nearest Prime number

Last Updated : 02 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given the head node of a linked list, the task is to replace all the values of the nodes with the nearest prime number. If more than one prime number exists at an equal distance, choose the smaller one.

Examples:

Input: head = 2 → 6 → 10
Output: 2 → 5 → 11
Explanation: The nearest prime of 2 is 2 itself. The nearest primes of 6 are 5 and 7, since 5 is smaller so, 5 will be chosen. The nearest prime of 10 is 11.

image-1

Input: head = 1 → 15 → 20
Output: 2 → 13 → 19
Explanation: The nearest prime of 1 is 2. The nearest primes of 15 are 13 and 17, since 13 is smaller so, 13 will be chosen. The nearest prime of 20 is 19.

image-2

Interesting Fact: The gap between two consecutive primes is never greater than 72 for numbers less than or equal to 10⁶. This means that for most practical cases, the nearest prime is always within a small range.

[Naive Approach] Nearest Prime for Nodes Using Trial Division

Idea is to traverse the Linked List and check if the current number is a prime number, then the number itself is the nearest prime number for it, so no need to replace its value, if the current number is not a prime number, visit both sides of the current number and replace the value with nearest prime number.

Step-by-Step Implementation

  • Initialize a node say, temp = head, to traverse the Linked List.
  • Run a loop till temp != NULL,
  • Traverse the linked list.
  • Initialize three variables num, num1, and num2 with the current node value.
  • If the current node value is 1, replace it with 2.
  • If the current node is not prime, we have to visit both sides of the number to find the nearest prime number
    • and decrease the number by 1 till we get a prime number.
      • while (!isPrime(num1)), num1--.
    • increase the number by 1 till we get a prime number.
      • while (!isPrime(num2)), num2++.
  • Now update the node value with the nearest prime number.

Below is the implementation for the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int val;
    Node* next;
    Node(int num) {
        val = num;
        next = NULL;
    }
};

bool isPrime(int n) {
    if (n == 1)
        return false;
    if (n == 2 || n == 3)
        return true;
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

Node* primeList(Node* head) {
    Node* temp = head;
    while (temp != NULL) {
        int num = temp->val, num1, num2;
        num1 = num2 = num;
        if (num == 1) {
            temp->val = 2;
            temp = temp->next;
            continue;
        }
        while (!isPrime(num1)) {
            num1--;
        }
        while (!isPrime(num2)) {
            num2++;
        }
        if (num - num1 > num2 - num) {
            temp->val = num2;
        }
        else {
            temp->val = num1;
        }
        temp = temp->next;
    }
    return head;
}

// Driver code
int main() {

    Node* head = new Node(2);
    head->next = new Node(6);
    head->next->next = new Node(10);
    Node* ans = primeList(head);
    while (ans != NULL) {
        cout << ans->val << " ";
        ans = ans->next;
    }
    return 0;
}
Java
// Java code for the above approach:
import java.util.*;

class Node {
    public int val;
    public Node next;
    public Node(int num)
    {
        val = num;
        next = null;
    }
}

class GFG {
    public static boolean isPrime(int n)
    {
        if (n == 1)
            return false;
        if (n == 2 || n == 3)
            return true;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static Node primeList(Node head)
    {
        Node temp = head;
        while (temp != null) {
            int num = temp.val, num1, num2;
            num1 = num2 = num;
            if (num == 1) {
                temp.val = 2;
                temp = temp.next;
                continue;
            }
            while (!isPrime(num1)) {
                num1--;
            }
            while (!isPrime(num2)) {
                num2++;
            }
            if (num - num1 > num2 - num) {
                temp.val = num2;
            }
            else {
                temp.val = num1;
            }
            temp = temp.next;
        }
        return head;
    }

    // Driver code
    public static void main(String[] args)
    {
        Node head = new Node(2);
        head.next = new Node(6);
        head.next.next = new Node(10);
        Node ans = primeList(head);
        while (ans != null) {
            System.out.print(ans.val + " ");
            ans = ans.next;
        }
    }
}

// This code is contributed by prasad264
Python
# Import math module to use sqrt function
import math

# Define a Node class with val and next attributes
class Node:
    def __init__(self, num):
        self.val = num
        self.next = None

# Define a function to check if a number is prime        
def is_prime(n):
    # 1 is not a prime number
    if n == 1:
        return False
      
    # 2 and 3 are prime numbers
    if n == 2 or n == 3:
        return True
      
    # Check if the number has any factor between 2 and sqrt(n)
    for i in range(2, int(math.sqrt(n))+1):
      if n % i == 0:
          return False

    return True

# Define a function to update the values of the nodes based on prime numbers
def primeList(head):
    # Set temp variable to head node
    temp = head
    
    # Loop through the linked list
    while temp != None:
          # Get the value of the current node
        num = temp.val
        
        # Initialize num1 and num2 to num
        num1, num2 = num, num
        
        # If the node value is 1, update it to 2 and move to next node
        if num == 1:
            temp.val = 2
            temp = temp.next
            continue
        
        # Find the nearest prime numbers on either side of num
        while not is_prime(num1):
            num1 -= 1
        while not is_prime(num2):
            num2 += 1
            
        # Update the node value based on which nearest prime is
        # closer to num
        if num - num1 > num2 - num:
            temp.val = num2
        else:
            temp.val = num1
        
        # Move to next node
        temp = temp.next
    return head

# Driver code
if __name__ == '__main__':
    head = Node(2)
    head.next = Node(6)
    head.next.next = Node(10)
    
    ans = primeList(head)
    
    # Print the updated values of nodes in the linked list
    while ans != None:
        print(ans.val, end=' ')
        ans = ans.next
C#
using System;

public class Node {
    public int val;
    public Node next;
    public Node(int num)
    {
        val = num;
        next = null;
    }
}

class GfG {
    public static bool IsPrime(int n){
        
        if (n == 1)
            return false;
        if (n == 2 || n == 3)
            return true;
        for (int i = 2; i <= Math.Sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static Node primeList(Node head){
        
        Node temp = head;
        while (temp != null) {
            int num = temp.val, num1, num2;
            num1 = num2 = num;
            if (num == 1) {
                temp.val = 2;
                temp = temp.next;
                continue;
            }
            while (!IsPrime(num1)) {
                num1--;
            }
            while (!IsPrime(num2)) {
                num2++;
            }
            if (num - num1 > num2 - num) {
                temp.val = num2;
            }
            else {
                temp.val = num1;
            }
            temp = temp.next;
        }
        return head;
    }

    public static void Main()
    {
        Node head = new Node(2);
        head.next = new Node(6);
        head.next.next = new Node(10);
        Node ans = primeList(head);
        while (ans != null) {
            Console.Write(ans.val + " ");
            ans = ans.next;
        }
    }
}
JavaScript
// JavaScript code for the above approach:

// Node class with val and next attributes
class Node {
    constructor(num)
    {
        this.val = num;
        this.next = null;
    }
}

// function to check if a number is prime 
function isPrime(n)
{
      // 1 is not a prime number
    if (n == 1)
        return false;
      // 2 and 3 are prime numbers
    if (n == 2 || n == 3)
        return true;
      
      // Check if the number has any factor between 2 and sqrt(n)
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}

// function to update the values of the nodes based on prime numbers
function primeList(head)
{
      // Set temp variable to head node
    let temp = head;
  
      // Loop through the linked list
    while (temp != null) {
        let num = temp.val, num1, num2;
        num1 = num2 = num;
      
          // If the node value is 1, update it to 2 and move to next node
        if (num == 1) {
            temp.val = 2;
            temp = temp.next;
            continue;
        }
      
          // Find the nearest prime numbers on either side of num
        while (!isPrime(num1)) {
            num1--;
        }
        while (!isPrime(num2)) {
            num2++;
        }
      
          // Update the node value based on which nearest prime is closer to num
        if (num - num1 > num2 - num) {
            temp.val = num2;
        }
        else {
            temp.val = num1;
        }
      
          // move to next node
        temp = temp.next;
    }
  
    return head;
}

// Driver code
let head = new Node(2);
head.next = new Node(6);
head.next.next = new Node(10);

// Function call
let ans = primeList(head);

let res = ""
while (ans != null) {
    res += ans.val;
    res += " ";
    ans = ans.next;
}

console.log(res);

Output
2 5 11 

Time Complexity: O(n × √m), where n is the number of nodes and m is the average node value, due to repeated trial division in isPrime().
Auxiliary Space: O(1), as no extra memory is used except for a few variables (excluding input/output and call stack).

[Expected Approach] Using Sieve of Eratosthenes

The Sieve of Eratosthenes is used in the findPrimes() function to efficiently precompute all prime numbers up to twice the maximum value in the linked list.

Note: We go up to 2 × max_val to ensure that for any number in the list, a greater nearest prime (if needed) always exists within that bound.

Step-by-Step Implementation

  • Traverse the linked list to find the maximum node value.
  • Use the maximum value to generate a list of prime numbers up to 2 * max_val.
  • Traverse the linked list again and for each node:
    • If the value is 1, set it to 2 (the smallest prime).
    • Otherwise, find the nearest prime numbers on both sides of the current value using the list of primes.
    • Update the node's value to the closest prime. If equidistant, choose the smaller one.
  • Return the head of the updated linked list.
  • Create a linked list and call the prime_list() function to update its values.
  • Print the updated values from the linked list.
C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int val;
    Node* next;

    Node(int num) {
        val = num;
        next = NULL;
    }
};

vector<int> findPrimes(int n) {
    vector<int> primes(n + 1, 1);
    primes[0] = 0;
    primes[1] = 0;
    for (int i = 2; i * i <= n; i++) {
        if (primes[i]) {
            for (int j = i * i; j <= n; j += i) {
                primes[j] = 0;
            }
        }
    }
    return primes;
}

Node* primeList(Node* head) {
    int max_num = 0;
    Node* temp = head;
    while (temp != NULL) {
        max_num = max(max_num, temp->val);
        temp = temp->next;
    }

    vector<int> primes = findPrimes(2 * max_num);
    
    temp = head;
    while (temp != NULL) {
        int num = temp->val;
        
        if (num == 1) {
            temp->val = 2;
        } else {
            int num1 = num, num2 = num;
            while (!primes[num1]) {
                num1--;
            }
            while (!primes[num2]) {
                num2++;
            }
            
            if (num - num1 > num2 - num) {
                temp->val = num2;
            } else {
                temp->val = num1;
            }
        }
        
        temp = temp->next;
    }
    
    return head;
}

int main() {
    Node* head = new Node(2);
    head->next = new Node(6);
    head->next->next = new Node(10);
    Node* ans = primeList(head);
    while (ans != NULL) {
        cout << ans->val << " ";
        ans = ans->next;
    }
    return 0;
}
Java
import java.util.*;

class GfG {

    static class Node {
        int val;
        Node next;

        Node(int num) {
            val = num;
            next = null;
        }
    }

    static List<Integer> findPrimes(int n) {
        List<Integer> primes = new ArrayList<>
        (Collections.nCopies(n + 1, 1));
        primes.set(0, 0);
        primes.set(1, 0);
        for (int i = 2; i * i <= n; i++) {
            if (primes.get(i) == 1) {
                for (int j = i * i; j <= n; j += i) {
                    primes.set(j, 0);
                }
            }
        }
        return primes;
    }

    static Node primeList(Node head) {
        int maxNum = 0;
        Node temp = head;
        while (temp != null) {
            maxNum = Math.max(maxNum, temp.val);
            temp = temp.next;
        }

        List<Integer> primes = findPrimes(2 * maxNum);
        
        temp = head;
        while (temp != null) {
            int num = temp.val;
            
            if (num == 1) {
                temp.val = 2;
            } else {
                int num1 = num, num2 = num;
                while (primes.get(num1) == 0) {
                    num1--;
                }
                while (primes.get(num2) == 0) {
                    num2++;
                }
                
                if (num - num1 > num2 - num) {
                    temp.val = num2;
                } else {
                    temp.val = num1;
                }
            }
            
            temp = temp.next;
        }
        
        return head;
    }

    public static void main(String[] args) {
        Node head = new Node(2);
        head.next = new Node(6);
        head.next.next = new Node(10);
        Node ans = primeList(head);
        while (ans != null) {
            System.out.print(ans.val + " ");
            ans = ans.next;
        }
    }
}
Python
class Node:
    def __init__(self, num):
        self.val = num
        self.next = None

def findPrimes(n):
    primes = [1] * (n + 1)
    primes[0] = 0
    primes[1] = 0
    i = 2
    while i * i <= n:
        if primes[i]:
            j = i * i
            while j <= n:
                primes[j] = 0
                j += i
        i += 1
    return primes

def primeList(head):
    maxNum = 0
    temp = head
    while temp is not None:
        maxNum = max(maxNum, temp.val)
        temp = temp.next

    primes = findPrimes(2 * maxNum)
    
    temp = head
    while temp is not None:
        num = temp.val
        
        if num == 1:
            temp.val = 2
        else:
            num1, num2 = num, num
            while not primes[num1]:
                num1 -= 1
            while not primes[num2]:
                num2 += 1
            
            if num - num1 > num2 - num:
                temp.val = num2
            else:
                temp.val = num1
        
        temp = temp.next
    
    return head

head = Node(2)
head.next = Node(6)
head.next.next = Node(10)
ans = primeList(head)
while ans is not None:
    print(ans.val, end=" ")
    ans = ans.next
C#
using System;
using System.Collections.Generic;

class GfG {

    class Node {
        public int val;
        public Node next;

        public Node(int num) {
            val = num;
            next = null;
        }
    }

    static List<int> findPrimes(int n) {
        List<int> primes = new List<int>(new int[n + 1]);
        for (int i = 0; i <= n; i++) primes[i] = 1;
        primes[0] = 0;
        primes[1] = 0;
        for (int i = 2; i * i <= n; i++) {
            if (primes[i] == 1) {
                for (int j = i * i; j <= n; j += i) {
                    primes[j] = 0;
                }
            }
        }
        return primes;
    }

    static Node primeList(Node head) {
        int maxNum = 0;
        Node temp = head;
        while (temp != null) {
            maxNum = Math.Max(maxNum, temp.val);
            temp = temp.next;
        }

        List<int> primes = findPrimes(2 * maxNum);
        
        temp = head;
        while (temp != null) {
            int num = temp.val;
            
            if (num == 1) {
                temp.val = 2;
            } else {
                int num1 = num, num2 = num;
                while (primes[num1] == 0) {
                    num1--;
                }
                while (primes[num2] == 0) {
                    num2++;
                }
                
                if (num - num1 > num2 - num) {
                    temp.val = num2;
                } else {
                    temp.val = num1;
                }
            }
            
            temp = temp.next;
        }
        
        return head;
    }

    static void Main() {
        Node head = new Node(2);
        head.next = new Node(6);
        head.next.next = new Node(10);
        Node ans = primeList(head);
        while (ans != null) {
            Console.Write(ans.val + " ");
            ans = ans.next;
        }
    }
}
JavaScript
function Node(num) {
    this.val = num;
    this.next = null;
}

function findPrimes(n) {
    const primes = new Array(n + 1).fill(1);
    primes[0] = 0;
    primes[1] = 0;
    for (let i = 2; i * i <= n; i++) {
        if (primes[i]) {
            for (let j = i * i; j <= n; j += i) {
                primes[j] = 0;
            }
        }
    }
    return primes;
}

function primeList(head) {
    let maxNum = 0;
    let temp = head;
    while (temp !== null) {
        maxNum = Math.max(maxNum, temp.val);
        temp = temp.next;
    }

    const primes = findPrimes(2 * maxNum);
    
    temp = head;
    while (temp !== null) {
        const num = temp.val;
        
        if (num === 1) {
            temp.val = 2;
        } else {
            let num1 = num, num2 = num;
            while (!primes[num1]) {
                num1--;
            }
            while (!primes[num2]) {
                num2++;
            }
            
            if (num - num1 > num2 - num) {
                temp.val = num2;
            } else {
                temp.val = num1;
            }
        }
        
        temp = temp.next;
    }
    
    return head;
}

const head = new Node(2);
head.next = new Node(6);
head.next.next = new Node(10);
let ans = primeList(head);
while (ans !== null) {
    process.stdout.write(ans.val + " ");
    ans = ans.next;
}

Output
2 5 11 

Time Complexity: O(n + max_val × log(log(max_val))), where n is the number of nodes and max_val is the maximum node value, due to traversing the list and using the Sieve of Eratosthenes.
Auxiliary Space: O(max_val), for storing the sieve (prime number array).



Next Article
Article Tags :
Practice Tags :

Similar Reads