Given a linked list of integers, the task is to determine if there exists a subsequence of prime numbers whose sum is a perfect square.
Examples:
Input: 13 -> 5 -> 10 -> 7 -> 2 -> NULL
Output: Yes
Explanation: The subsequence of primes with a sum of 25 (13, 5, and 7) is a perfect square since the output is “Yes”.Input: 4 -> 11 -> 6 -> 5 -> NULL
Output: Yes
Explanation: The subsequence of primes with a sum of 16 (11, and 5) is a perfect square since the output is “Yes”.Input: 5 -> 1 -> 14 -> 6 -> 8 -> NULL
Output: No
Explanation: The linked list does not contain any subsequence of prime numbers. Therefore, the output is “No”.
Approach: This can be solved with the following idea:
This approach involves identifying all prime numbers in the linked list, computing all possible sub-sequences of prime numbers, and checking whether any of the sub-sequences have a sum that is a perfect square. If a sub-sequence with a sum that is a perfect square is found, return true; otherwise, return false.
Here are the steps of the approach:
-
Traverse the linked list and identify all prime number nodes in it:
- The first step is to traverse the linked list and identify all prime numbers in it. This can be done by iterating over each node in the linked list and checking whether its value is a prime number.
-
Compute all possible sub-sequences of prime numbers in the linked list:
- Once all prime numbers in the linked list have been identified, the next step is to compute all possible sub-sequences of prime numbers.
-
This can be done using two nested loops:
- The outer loop iterates over each node in the linked list,
- And the inner loop iterates over each subsequent node to create all possible sub-sequences.
-
Check whether any of the sub-sequences have a sum that is a perfect square:
- For each sub-sequence of prime numbers computed in the previous step, check whether its sum is a perfect square. This can be done by computing the square root of the sum and checking whether it is an integer. If a sub-sequence with a sum that is a perfect square is found, return true.
-
Return false if no sub-sequence with a sum that is a perfect square is found:
- If none of the sub-sequences of prime numbers has a sum that is a perfect square, return false to indicate that no such sub-sequence exists in the linked list.
Below is the implementation of the above approach:
// C++ code for the above approach: #include <bits/stdc++.h> using namespace std;
struct Node {
int val;
Node* next;
}; // To check whether a number is // prime or not bool isPrime( int num)
{ if (num <= 1)
return false ;
for ( int i = 2; i <= sqrt (num); i++) {
if (num % i == 0)
return false ;
}
return true ;
} // To check whether a subsequence exist // of prime number having perfect // square sum bool hasSubsequenceWithSumAsPerfectSquare(Node* head)
{ unordered_map< int , Node*> sumToNode;
int sum = 0;
sumToNode[sum] = nullptr;
int index = 0;
while (head) {
if (isPrime(head->val)) {
sum += head->val;
if ( sqrt (sum) == ( int ) sqrt (sum)) {
return true ;
}
if (sumToNode.count(sum - ( int ) sqrt (sum)) > 0) {
Node* temp
= sumToNode[sum - ( int ) sqrt (sum)];
if (temp && temp->next
&& temp->next->next == head) {
return true ;
}
}
sumToNode[sum] = head;
}
head = head->next;
index++;
}
return false ;
} // Driver code int main()
{ Node* head = new Node{ 13, nullptr };
head->next = new Node{ 5, nullptr };
head->next->next = new Node{ 10, nullptr };
head->next->next->next = new Node{ 7, nullptr };
head->next->next->next->next = new Node{ 2, nullptr };
// Function call
bool hasSubsequence
= hasSubsequenceWithSumAsPerfectSquare(head);
if (hasSubsequence) {
cout << "Yes\n" ;
}
else {
cout << "No\n" ;
}
return 0;
} |
// Java code for the above approach: import java.util.*;
class Node {
int val;
Node next;
public Node( int val, Node next)
{
this .val = val;
this .next = next;
}
} public class SubsequenceWithPerfectSquareSum {
// To check whether a number is prime or not
public static boolean isPrime( int num)
{
if (num <= 1 )
return false ;
for ( int i = 2 ; i <= Math.sqrt(num); i++) {
if (num % i == 0 )
return false ;
}
return true ;
}
// To check whether a subsequence exists
// with prime numbers having perfect square sum
public static boolean
hasSubsequenceWithSumAsPerfectSquare(Node head)
{
Map<Integer, Node> sumToNode = new HashMap<>();
int sum = 0 ;
sumToNode.put(sum, null );
int index = 0 ;
while (head != null ) {
if (isPrime(head.val)) {
sum += head.val;
if (Math.sqrt(sum) == ( int )Math.sqrt(sum)) {
return true ;
}
if (sumToNode.containsKey(
sum - ( int )Math.sqrt(sum))) {
Node temp = sumToNode.get(
sum - ( int )Math.sqrt(sum));
if (temp != null && temp.next != null
&& temp.next.next == head) {
return true ;
}
}
sumToNode.put(sum, head);
}
head = head.next;
index++;
}
return false ;
}
// Driver code
public static void main(String[] args)
{
Node head = new Node( 13 , null );
head.next = new Node( 5 , null );
head.next.next = new Node( 10 , null );
head.next.next.next = new Node( 7 , null );
head.next.next.next.next = new Node( 2 , null );
// Function call
boolean hasSubsequence
= hasSubsequenceWithSumAsPerfectSquare(head);
if (hasSubsequence) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
} // This code is contributed by shivamgupta0987654321 |
# python3 code for the above approach: import math
class Node:
def __init__( self , val):
self .val = val
self . next = None
# To check whether a number is prime or not def isPrime(num):
if num < = 1 :
return False
for i in range ( 2 , int (math.sqrt(num)) + 1 ):
if num % i = = 0 :
return False
return True
# To check whether a subsequence exists of prime numbers # having a perfect square sum def hasSubsequenceWithSumAsPerfectSquare(head):
sumToNode = {}
sum = 0
sumToNode[ sum ] = None
index = 0
while head:
if isPrime(head.val):
sum + = head.val
if int (math.sqrt( sum )) * * 2 = = sum :
return True
if sum - int (math.sqrt( sum )) in sumToNode:
temp = sumToNode[ sum - int (math.sqrt( sum ))]
if temp and temp. next and temp. next . next = = head:
return True
sumToNode[ sum ] = head
head = head. next
index + = 1
return False
# Driver code if __name__ = = "__main__" :
head = Node( 13 )
head. next = Node( 5 )
head. next . next = Node( 10 )
head. next . next . next = Node( 7 )
head. next . next . next . next = Node( 2 )
# Function call
hasSubsequence = hasSubsequenceWithSumAsPerfectSquare(head)
if hasSubsequence:
print ( "Yes" )
else :
print ( "No" )
# This code is contributed by shivamgupta0987654321 |
// C# code for the above approach using System;
using System.Collections.Generic;
public class Node {
public int val;
public Node next;
} public class GFG {
// To check whether a number is
// prime or not
static bool IsPrime( int num)
{
if (num <= 1)
return false ;
for ( int i = 2; i <= Math.Sqrt(num); i++) {
if (num % i == 0)
return false ;
}
return true ;
}
// To check whether a subsequence exist
// of prime number having perfect
// square sum
static bool
HasSubsequenceWithSumAsPerfectSquare(Node head)
{
Dictionary< int , Node> sumToNode
= new Dictionary< int , Node>();
int sum = 0;
int index = 0;
sumToNode[sum] = null ;
while (head != null ) {
if (IsPrime(head.val)) {
sum += head.val;
if (Math.Sqrt(sum) == ( int )Math.Sqrt(sum)) {
return true ;
}
if (sumToNode.ContainsKey(
sum - ( int )Math.Sqrt(sum))) {
Node temp
= sumToNode[sum
- ( int )Math.Sqrt(sum)];
if (temp != null && temp.next != null
&& temp.next.next == head) {
return true ;
}
}
sumToNode[sum] = head;
}
head = head.next;
index++;
}
return false ;
}
// Driver code
static void Main()
{
Node head = new Node{ val = 13, next = null };
head.next = new Node{ val = 5, next = null };
head.next.next = new Node{ val = 10, next = null };
head.next.next.next
= new Node{ val = 7, next = null };
head.next.next.next.next
= new Node{ val = 2, next = null };
// Function call
bool hasSubsequence
= HasSubsequenceWithSumAsPerfectSquare(head);
if (hasSubsequence) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
} // This code is contributed by Susobhan Akhuli |
class Node { constructor(val, next) {
this .val = val;
this .next = next;
}
} // To check whether a number is // prime or not function isPrime(num) {
if (num <= 1) {
return false ;
}
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false ;
}
}
return true ;
} // To check whether a subsequence exist // of prime number having perfect // square sum function hasSubsequenceWithSumAsPerfectSquare(head) {
const sumToNode = new Map();
let sum = 0;
sumToNode.set(sum, null );
while (head !== null ) {
if (isPrime(head.val)) {
sum += head.val;
if (Math.sqrt(sum) === Math.floor(Math.sqrt(sum))) {
return true ;
}
if (sumToNode.has(sum - Math.floor(Math.sqrt(sum)))) {
const temp = sumToNode.get(sum - Math.floor(Math.sqrt(sum)));
if (temp !== null && temp.next !== null && temp.next.next === head) {
return true ;
}
}
sumToNode.set(sum, head);
}
head = head.next;
}
return false ;
} // Driver code const head = new Node(13, null );
head.next = new Node(5, null );
head.next.next = new Node(10, null );
head.next.next.next = new Node(7, null );
head.next.next.next.next = new Node(2, null );
// Function call const hasSubsequence = hasSubsequenceWithSumAsPerfectSquare(head); if (hasSubsequence) {
console.log( "Yes" );
} else {
console.log( "No" );
} |
Yes
Time Complexity: O(N*sqrt(S)), where N is the number of nodes in the linked list and S is the sum of prime numbers encountered in the linked list.
Auxiliary Space: O(N), as we are storing a node pointer for each possible value of the sum of prime numbers encountered.