Replace the values of the nodes with the nearest Prime number
Last Updated :
02 May, 2025
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.
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.
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);
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;
}
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).
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read